Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define template specialization in cpp?

I can define a specialized function in a cpp like so...

// header

template<typename T>
void func(T){}

template<>
void func<int>(int);

// cpp

template<>
void func<int>(int)
{}

How can I define a method in a specialized class in a cpp? Like so (which doesn't work, I get error C2910: 'A<int>::func' : cannot be explicitly specialized)...

// header

template<typename T>
struct A
{
    static void func(T){}
};

template<>
struct A<int>
{
    static void func(int);
};

// cpp

template<>
void A<int>::func(int)
{}
like image 706
David Avatar asked Oct 23 '12 16:10

David


People also ask

What is template specialization used for?

It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.

How many types of specialization are there in C++?

How many types of specialization are there in c++? Explanation: There are two types of specialization. They are full specialization and partial specialization.

What are the two types of templates in C++?

Instead the programmer can write a C++ template based function that will work with all data types. There are two types of templates in C++, function templates and class templates.

What is a template class C++?

The relationship between a class template and an individual class is like the relationship between a class and an individual object. An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated.


1 Answers

Use following syntax in your .cpp file:

void A<int>::func(int)
{
}

This is Visual C++ kinda feature.

See MSDN C2910 error description for details:

This error will also be generated as a result of compiler conformance work that was done in Visual Studio .NET 2003:. For code will be valid in the Visual Studio .NET 2003 and Visual Studio .NET versions of Visual C++, remove template <>.

like image 108
Rost Avatar answered Sep 25 '22 23:09

Rost