如何转发声明c++模板类?

时间:2021-02-26 20:56:45

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?

有人如何在头文件中声明此类?

2 个解决方案

#1


73  

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.

请注意,默认值位于前向声明中,而不是实际定义中。

#2


6  

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!

您只能为模板的第一个声明声明模板的默认参数。如果要允许用户转发声明类模板,则应提供转发标头。如果你想使用默认值转发声明别人的类模板,那你就不走运了!

#1


73  

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.

请注意,默认值位于前向声明中,而不是实际定义中。

#2


6  

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!

您只能为模板的第一个声明声明模板的默认参数。如果要允许用户转发声明类模板,则应提供转发标头。如果你想使用默认值转发声明别人的类模板,那你就不走运了!