C ++模板专业化成员函数的定义 [英] Definition of C++ template specialization member function

查看:72
本文介绍了C ++模板专业化成员函数的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下课程和专长。我将如何为模板类以及类定义之外的两个专业实现函数体?显然,每个函数实现都需要声明为 inline

Given the following class and specializations. How would I implement the function bodies for the template class and both specializations outside of the class definition? Obviously, each function implementation would need to be declared inline.

template <typename T1, typename = void>
struct MyClass
{
    void func();
};
template <typename T1>
struct MyClass<T1, std::enable_if_t<std::is_integral<T1>::value>>
{
    void func();
};
template <typename T1>
struct MyClass<T1, std::enable_if_t<std::is_floating_point<T1>::value>>
{
    void func();
};


推荐答案

对a进行类外定义模板类的成员函数,您可以重复模板参数,以便形成类的名称。

To have an out-of-class definition of a member function of a template class, you repeat the template arguments so you can form the name of the class.

基本上,定义此 func( )


template <typename T1, typename = void>
struct MyClass
{
    void func();
};


您会这样写:

template <typename T1, typename T2>
void MyClass<T1, T2>::func() {}

要对此进行定义一个:


template <typename T1>
struct MyClass<T1, std::enable_if_t<std::is_integral<T1>::value>>
{
    void func();
};


您会这样写:

template <typename T1>
void MyClass<T1, std::enable_if_t<std::is_integral<T1>::value>>::func() {}

在Godbolt上生活

这篇关于C ++模板专业化成员函数的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆