C ++ compiler error when developing templates

I would like to specialize the template method for class C, which itself is templated by int parameter.

How to do it?

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

Specialization for test () fails with "Too many lists of template parameters in the void test () declaration."

+3
source share
2 answers

Partial specialization of the function template is not allowed. At

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

You do not need the first template<>in your partial specialization test<C<D>>. Moreover, you can only partially specialize class templates, not function templates. Maybe something like this:

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
+1

Source: https://habr.com/ru/post/1750701/


All Articles