【问题标题】:template specialisation for a whole set of parameters整套参数的模板特化
【发布时间】:2011-04-17 16:42:44
【问题描述】:

可能很容易解决,但很难找到解决方案:

是否可以(部分)专门化一整套类型? 在示例中,“Foo”应部分专门用于 (T,int) 和 (T,double),只有一个模板定义。

我能做的是为 (T,int) 定义一个特化。见下文。但是,它应该适用于 (T,int) and (T,double) 只有一个函数定义(没有代码加倍)。

template <typename T,typename T2>
struct Foo
{
  static inline void apply(T a, T2 b) 
  {
    cout << "we are in the generic template definition" << endl;
  }
};

// partial (T,*)
template <typename T>
struct Foo<T, int >     // here something needed like T2=(int, double)
{
  static inline void apply(T a, T2 b) 
  {
    cout << "we are in the partial specialisation for (T,int)" << endl;
  }
};

任何想法如何使用一个模板定义来部分专门化 (T,int) 和 (T,double) ?

【问题讨论】:

  • 编译器怎么可能知道在这里做什么?它怎么知道你想打印"partial double"等?
  • 输出仅用于了解使用了哪个函数定义。

标签: c++ templates


【解决方案1】:

如果我正确理解了您的问题,那么您可以编写一个基类模板并从中派生,如下图所示:

template <typename T, typename U>
struct Foo_Base
{
  static inline void apply(T a) 
  {
    cout << "we are in the partial specialisation Foo_Base(T)" << endl;
  }
};

template <typename T>
struct Foo<T, int> : Foo_Base<T, int> {};

template <typename T>
struct Foo<T, double> : Foo_Base<T, double> {};

虽然它不是一个模板定义(如您所要求的),但您可以避免代码重复。

演示:http://www.ideone.com/s4anA

【讨论】:

  • 感谢您的回答。不幸的是,您使用了在原始问题中应用的情况,这不是故意的。 “两种”类型都需要作为函数参数。抱歉,我没有具体说明。
  • @Frank:现在看看我的答案。现在Foo_Base 需要两个类型参数,因此我在派生时传递它们
  • 好主意!你说的对。它不是一个定义,但可以避免代码加倍。就目前而言它有效。
【解决方案2】:

我相信您可以使用 Boost 的 enable_if 来实现这一点,从而为您想要的类型启用部分专业化。第 3.1 节展示了如何,并给出了这个例子:

template <class T, class Enable = void> 
class A { ... };

template <class T>
class A<T, typename enable_if<is_integral<T> >::type> { ... };

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 2015-02-19
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多