3

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

我该怎么做呢?

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() 声明中的模板参数列表过多”。

4

2 回答 2

2

不允许函数模板部分特化。做

template <int D>  
void test () {cout << C<D>::foo() << endl;}
于 2010-06-18T15:33:37.517 回答
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
于 2010-06-18T15:26:22.933 回答