2012-05-15 101 views
2

要有一种鸭子类型的,我做鸭打字C++(通过其非类型模板参数的值专门的模板功能)

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 class, function specialization (我不想额外PARAM添加到功能)

我想这样做

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'。

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

+0

这可能有助于在main()中给出如何使用D的示例。 –

+0

对不起,主要是我打算使用D.C仅用于做出“可能存在或不存在在那里“ –

回答

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只是typedef S的std::integral_constant<bool, true>false,RESP。

+0

亲爱的jpalecek,谢谢。问题出现在我想要使用该类的成员时。在我的解决方案中,我总是传递一个V *,我基本上将它用作“this”。 这是我想要的模板的主要原因 void f();里面D(这将采取V的角色) –

+0

@FabioDallaLibera:是的。我认为你的解决方案是可以的。我在答案中增加了另一种可能性。 – jpalecek

+0

谢谢你,你的第二个解决方案非常接近http://stackoverflow.com/questions/2349995/template-class-function-specialization 我想这是唯一可行的方法来做到这一点,我会坚持你的解决方案,坦克你 –