2

有一种鸭子打字,我做

template<bool b>
struct A{
  static template<typename V> f1(V*, [other params]);     
  static template<typename V> f2(V*, [other params]);            
};

template<> template<typename T>
void A<false>::f1(V*, [other params]){}

template<> template<typename T>
void A<true>::f1(V*, [other params]){
   ...some code...
}  

template<int flags>
struct V{
  void f(){
     A<flags&Some compile time conditions>::f1 (this,[params]);
     A<flags&Some compile time conditions>::f2 (this,[params]); 
  } 
};

你认为有没有更优雅的解决方案,不是模板类,函数特化 (我不想给函数添加额外的参数)

我想做类似的事情

template<int X> struct C{
 void f(){std::cout<<"C::f"<<std::endl;};
};


template<> struct C<0>{
};


template<int X> struct D{
 C<X> c;

 template<bool b>
 void f();

 void g(){
  f<X!=0>();
 }

};

template<>
template<int X> 
void D<X>::f<true>{
c.f();
};

template<int X>  
 template<>
 void D<X>::f<false>{};


int main(){
 D<3> ch;
 ch.g();

 D<0> cn;
 cn.g();

}

但这不是有效的代码,我收到错误:template-id 'f' used as a declarator。

有没有办法通过其非类型模板参数的值来专门化模板函数?

4

1 回答 1

1
template<>
template<int X> 
void D<X>::f<true>(){
c.f();
};

template<int X>  
 template<>
 void D<X>::f<false>(){};

这是非法的(所有尝试都是)。当您专门化成员函数模板时,它的封闭类也必须专门化。

但是,您可以通过将函数包装在一个模板结构中来轻松克服这个问题,该结构将接受其模板参数。就像是

template <int X, bool B>
struct DXF;

template <int X>
struct DXF<X, true>
{
  static void f() { // B is true!
  }
};

template <int X>
struct DXF<X, false>
{
  static void f() { // B is false!
  }
};

并用DXF<X, (X!=0)>::f().

但是,您似乎只想专注于X==0. 在这种情况下,您可以只专注于:

template <>
void D<0>::f() {}

请注意,f在这种情况下不是成员模板。


您可以选择的另一个选择是重载。您可以将您包装int在某个模板的参数列表中,如下所示:

template<int X> struct D{
 C<X> c;

 void f(std::true_type*) { ... true code ... }
 void f(std::false_type_*) { ... false code ... }
 void g(){
  f((std::integral_constant<bool, X!=0>*)0);
 }

请注意, true_type 和 false_type 只是typedefsstd::integral_constant<bool, true>false,分别。

于 2012-05-15T15:13:10.933 回答