c++ - 一整套参数的模板特化

标签 c++ templates

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

是否有可能(部分地)特化一整套类型? 在示例中,“Foo”应该部分特化为 (T,int) 和 (T,double),只有一个模板定义。

我能做的是为 (T,int) 定义一个特化。见下文。但是,它应该用于 (T,int) (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) 部分特化它有什么想法吗?

最佳答案

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

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

关于c++ - 一整套参数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5694843/

相关文章:

javascript - drupal 6 和 jquery 1.4/1.5

python - 在 {{ super() }} 中替换 block

c++ - 如何检测USB设备的 "Over Current"事件?

c++ - Templated Defaulted 默认构造函数

c++ - 获取 QT 代码的纯 C++ 实现

c++ - 没有匹配的成员函数调用 'insert'

python - 如何在 Cython 中定义 C++ 模板函数类型?

c++ - 使用 Search 方法为普通类型 (int) 和指针的 const 创建数组类

c++ - C++中的大整数

c++ - 模板问题 - 将函数作为参数传递时遇到问题(非静态成员函数的使用无效)