以下示例编译并显示正确的最终结果。编辑:在打印三行的意义上。
#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();
}
类(class)LogUser_H
有一个调用结构中的函数的方法。 LogUser_CPP
旨在对我想将方法定义移出类定义并将其写在下面的扭曲做同样的事情。这样做我不再有 output
的定义而且我无法访问满足输出要求的结构中的函数。但是,我可以提供专门版本的结构并以这种方式进行编译。
如何删除两个专门的实现 void LogUser_CPP<struct normal>::print(void)
和 void LogUser_CPP<struct other>::print(void)
?想要用看起来像注释掉的实现的通用实现替换它们 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");
}
关于c++ - 将具有限制的通用模板移出类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33655818/