Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward declare a C++ template class?

Given a template class like the following:

template<typename Type, typename IDType=typename Type::IDType>
class Mappings
{
public:
    ...
    Type valueFor(const IDType& id) { // return value }
    ...
};

How can someone forward declare this class in a header file?

like image 724
Tron Thomas Avatar asked Oct 10 '22 07:10

Tron Thomas


People also ask

Can you forward declare a template?

You can declare default arguments for a template only for the first declaration of the template. If you want allow users to forward declare a class template, you should provide a forwarding header. If you want to forward declare someone else's class template using defaults, you are out of luck!

Can you forward declare in C?

In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

How do you declare a class template?

A class template must be declared before any instantiation of a corresponding template class. A class template definition can only appear once in any single translation unit. A class template must be defined before any use of a template class that requires the size of the class or refers to members of the class.

How do you forward a function declaration?

To write a forward declaration for a function, we use a declaration statement called a function prototype. The function prototype consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the prototype.


1 Answers

This is how you would do it:

template<typename Type, typename IDType=typename Type::IDType>
class Mappings;

template<typename Type, typename IDType>
class Mappings
{
public:
    ...
    Type valueFor(const IDType& id) { // return value }
    ...
};

Note that the default is in the forward declaration and not in the actual definition.

like image 137
Pubby Avatar answered Oct 13 '22 06:10

Pubby