模板特化上的C ++编译器错误

时间:2010-06-18 15:22:46

标签: c++ compiler-errors template-specialization

我想专门为一个C类本身的模板方法 由int参数模板化。

我该怎么做?

template <int D=1>
class C {
    static std::string  foo () { stringstream ss; ss << D << endl; return ss.str();}    
};

template <class X>
void test() { cout << "This is a test" << endl;}

template <>
template <int D>
void test<C<D> > () {cout << C<D>::foo() << endl;}

test()的特化失败,“void test()声明中的模板参数列表太多。”

2 个答案:

答案 0 :(得分:2)

不允许使用功能模板部分特化。做

template <int D>  
void test () {cout << C<D>::foo() << endl;}

答案 1 :(得分:1)

您不希望第一个template<>部分专注于test<C<D>>。此外,您只能部分地专门化类模板,而不是功能模板。这样的事情可能有用:

template <class X>
struct thing
{
    static void test() { cout << "This is a test" << endl;}
};

template <int D>
struct thing<C<D>>
{
    static void test() {cout << C<D>::foo() << endl;}
};

如果您的函数模板接受了一个参数,并使用它来推断模板参数,那么您可以使用重载获得类似的效果,如:

template <class X>
void test(const X&) { cout << "This is a test" << endl;}

template <int D>
void test(const C<D>&) {cout << C<D>::foo() << endl;}

test(3);  // calls first version
test(C<3>()); // calls second version