将具有限制的通用模板移出类定义

Moving a generic template with restrictions out of the class definition

本文关键字:移出 定义 有限制      更新时间:2023-10-16

以下示例编译并显示正确的最终结果。编辑:从印刷三行的意义上来说。

#include <iostream>
using namespace std;
struct normal
{
    static void log(const char * out) { cout << out << endl; }
};
struct other
{
    static void log(const char * out) { cout << out << endl; }
};
//Implementation inside the class declaration
template<typename output = normal>
class LogUser_H
{
public:
    void print() { output::log("template"); }
};
//Move Implementation moved out of the class declaration
template<typename output = normal>
class LogUser_CPP
{
public:
    void print();
};
//Specialised definitions
void LogUser_CPP<struct normal>::print(void) { normal::log("normal specialisation"); }
void LogUser_CPP<struct other>::print(void) { other::log("other specialisation"); }
//Template definition ?
//void LogUser_CPP</*??*/output/*??*/>::print(void)
//{
//    output::log("template");
//}
int main()
{
    LogUser_H<> H;
    H.print();
    LogUser_CPP<> C1;
    C1.print();
    LogUser_CPP<other> C2;
    C2.print();
}

LogUser_H有一个调用结构中函数的方法。LogUser_CPP的目的是对我想要将方法定义从类定义中移出并在下面编写它的扭曲进行同样的处理。这样一来,我就不再有output的定义,也无法获得满足输出要求的结构中的函数。然而,我可以提供struct的专用版本,并以这种方式进行编译。

如何删除两个专门的实现void LogUser_CPP<struct normal>::print(void)void LogUser_CPP<struct other>::print(void)?In想用一个通用实现来替换它们,看起来像注释掉的实现void LogUser_CPP</*??*/output/*??*/>::print(void)

编辑1:我尝试了以下方法:

//Specialised definitions
//void LogUser_CPP<struct normal>::print(void) { normal::log("normal specialisation"); }
//void LogUser_CPP<struct other>::print(void) { other::log("other specialisation"); }
template<>
void LogUser_CPP<>::print(void)
{
    output::log("template");
}

这将不会编译。

编辑2:我尝试了以下方法:

//Specialised definitions
//void LogUser_CPP<struct normal>::print(void) { normal::log("normal specialisation"); }
//void LogUser_CPP<struct other>::print(void) { other::log("other specialisation"); }
template<typename output>
void LogUser_CPP<>::print(void)
{
    output::log("template");
}

这将不会编译。错误为error C3211: 'LogUser_CPP<normal>::print' : explicit specialization is using partial specialization syntax, use template <> instead这可能是编译器特有的吗?这台计算机上有VS2013 Express。

使用:

template <>
void LogUser_CPP<normal>::print(void) { normal::log("normal specialisation"); }
template <>
void LogUser_CPP<other>::print(void) { other::log("other specialisation"); }

template<typename output>
void LogUser_CPP<output>::print(void)
{
    output::log("template");
}