Static template member function for template class

旧城冷巷雨未停 提交于 2019-12-06 16:15:07

You cannot partially specialize a function.

You can forward the work to another type:

template<class T1>
struct A;

template<class T1, class T2>
struct A_helper {
  static int f() {
    return A<T1>::f_simple<T2>();
  }
};
template<class T>
struct A_helper<T,T> {
  static int f() {
    return A<T>::f_special();
  }
};

template<class T1>
struct A{
  template<class T2>
  static int f(){return A_helper<T1,T2>::f()}
  template<class T2>
  static int f_simple(){return 0;}
  static int f_special(){return -1;}
};

or, more simply, with no A_helper:

template<class T1>
struct A{
  template<class T2>
  static int f(){return f2<T2>(std::is_same<T1,T2>{});}
  template<class T2>
  static int f2(std::true_type){
    static_assert(std::is_same<T1,T2>{}, "bob!");
    return -1;
  }
  tempalte<class T2>
  static int f2(std::false_type){return -1;}
};

you can use tag dispatching.

Another approach:

template<class T>struct tag{};

template<class T1>
struct A{
  template<class T2>
  static int f(){return f2(tag<T2>{});}
  template<class T2>
  static int f2(tag<T2>) {return 0;}
  static int f2(tag<T1>) {return -1;}
};

where we directly dispatch on the type of T2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!