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 クラス、関数の特殊化ではない、より洗練されたソリューションがあると思いますか (関数に余分なパラメーターを追加したくない)

私は次のようなことをしたいと思います

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' が宣言子として使用されています。

非型テンプレート パラメータの値によってテンプレート関数を特殊化する方法はありますか?

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は、それぞれとのtypedefsであることに注意してください。std::integral_constant<bool, true>false

于 2012-05-15T15:13:10.933 に答える