Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit specialization of a function template for a fully specialized class template

I'm trying to specialize a function within a specialization of a class template, but can't figure the right syntax:

template< typename T >
struct Foo {};

template<>
struct Foo< int >
{
  template< typename T >
  void fn();
};

template<> template<>
void Foo< int >::fn< char >() {} // error: too many template-parameter-lists

Here I'm trying to specialize fn for char, which is inside of Foo specialized for int. But the compiler doesn't like what I write. What should be the right syntax then?

like image 986
dragonroot Avatar asked Nov 27 '15 00:11

dragonroot


People also ask

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.

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 is the other name of full specialization?

Explanation: explicit specialization is another name of full specialization.

What are templates How are templates used to define classes and functions?

Class Templates like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. Following is a simple example of a template Array class.


1 Answers

You don't have to say that you're specializing twice.

You're only specializing one function template here

template<> void Foo<int>::fn<char>() {}

Live On Coliru

template< typename T >
struct Foo {};

template<>
struct Foo< int >
{
  template< typename T >
  void fn();
};

template<> void Foo<int>::fn<char>() {}

int main() {
    Foo<int> f;
    f.fn<char>();
}
like image 121
sehe Avatar answered Oct 06 '22 06:10

sehe