是否可以专门化一个模板类来获取额外的模板参数?

例如:

template <typename T>
struct X {
  void foo() { cerr << "Generic" << endl;}
};


template <>
template <bool b>
struct X<int> {
  void foo() { cerr << "Specialization" << endl;}
};

我无法使用 g++ 进行上述工作,但也许有一些技巧可以使这项工作有效。

编辑:我不想将模板 <bool b> 移动到基本模板 X,因为它只是 X<int>. 的功能
如果必须,有没有办法让用户不必为其指定任何值?我真的很想
一种不会走这条路的方法。

最佳答案

您可以更改主模板以接受代理特征类:

template <typename T>
struct Foo
{
    typedef typename T::type type;

    // work with "type"

    void static print() { std::cout << T::message << std::endl; }
}

然后定义特征类:
template <typename T>
struct traits
{
    typedef T type;
    static const char * const message  = "Generic";
};

现在您可以实例化 Foo<traits<double>>Foo<traits<int>> ,并且您可以将额外的行为封装到 traits 类中,您可以根据需要对其进行专门化。
template <>
struct traits<int>
{
    typedef int type;
    static const char * const message = "Specialized";
};

关于C++ 特化了一个模板类来接受一个额外的模板参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9950148/

10-11 23:04
查看更多