Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template method of template class specialization

Here is my code:

template<typename T1, typename T2> class MyClass
{
public:
    template<int num> static int DoSomething();
};

template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething()
{
    cout << "This is the common method" << endl;
    cout << "sizeof(T1) = " << sizeof(T1) << endl;
    cout << "sizeof(T2) = " << sizeof(T2) << endl;
    return num;
}

It works well. But when I try to add this

template<typename T1, typename T2> template<> int MyClass<T1, T2>::DoSomething<0>()
{
    cout << "This is ZERO!!!" << endl;
    cout << "sizeof(T1) = " << sizeof(T1) << endl;
    cout << "sizeof(T2) = " << sizeof(T2) << endl;
    return num;
}

I get compiller errors: invalid explicit specialization before «>» token template-id «DoSomething<0>» for «int MyClass::DoSomething()» does not match any template declaration

I use g++ 4.6.1 What should I do?

like image 537
antpetr89 Avatar asked Feb 14 '12 11:02

antpetr89


People also ask

What is a template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What are the two types of templates?

There are two types of templates in C++, function templates and class templates.

What is meant by template specialization Mcq?

Explanation: Template specialization is used when a different and specific implementation is to be used for a specific data type. In this program, We are using integer and character.

How is a template class different from a template function?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.


1 Answers

Unfortunately, you can't specialise a template that's a member of a class template, without specialising the outer template:

C++11 14.7.3/16: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

I think your best option is to add the extra parameter to MyClass, and then partially specialise that.

like image 174
Mike Seymour Avatar answered Oct 16 '22 20:10

Mike Seymour