【问题标题】:duck typing in C++ (specialize a template function by the value of its non-type template parameter)鸭子在 C++ 中键入(通过其非类型模板参数的值来专门化模板函数)
【发布时间】:2012-05-16 00:31:51
【问题描述】:

为了有一种鸭式打字,我愿意

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 (我不想在函数中添加额外的参数)

我想做类似的事情

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。

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

【问题讨论】:

  • 在 main() 中举例说明您计划如何使用 D 可能会有所帮助。
  • 抱歉,主要是我打算使用 D.C 仅用于制作“可能存在或不存在”的东西

标签: c++ templates


【解决方案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&lt;X, (X!=0)&gt;::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 分别是 std::integral_constant&lt;bool, true&gt;falsetypedefs。

【讨论】:

  • 亲爱的 jpalecek,谢谢。当我想使用班级成员时,问题就来了。在我的解决方案中,我总是传递一个 V*,我基本上将其用作“this”。这是我想要 template void f(); 的主要原因。在 D 内部(将扮演 V 的角色)
  • @FabioDallaLibera:是的。我认为您的解决方案还可以。我在回答中添加了另一种可能性。
  • 谢谢您,您的第二个解决方案与stackoverflow.com/questions/2349995/… 非常接近,因此我想这是唯一可行的方法,我会坚持您的解决方案,让您放心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多