简体   繁体   中英

C++ compiler error on template specialization

I would like to specialize a template method for a class C that is itself templated by an int parameter.

How do I do this?

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;}

The specialization for test() fails with "Too many template parameter lists in declaration of void test()".

Function template partial specialization is not allowed. Do

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

You don't want the first template<> on your partial specialisation of test<C<D>> . Moreover, you can only partially specialise class templates, not function templates. Something like this might work:

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;}
};

If your function template took an argument, and used that to infer the template argument, then you could get a similar effect using overloading, something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM