将具有限制的通用模板移出类定义
Moving a generic template with restrictions out of the class definition
以下示例编译并显示正确的最终结果。编辑:从印刷三行的意义上来说。
#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");
}
相关文章:
- 将字符移出范围的危险
- 将移出参数的最佳做法
- 是否可以将值分配给移出位置?
- 将键移出 std::map<> &&
- 移出某些元素后无法从矢量中删除
- 当鼠标移出窗口时,SFML 窗口会自行关闭
- 虚拟析构函数将对象移出 rodata 部分
- 将代码移出类定义时未扩展参数包
- 如何将变量从 for 循环中移出?
- 在移出向量上调用 size() 方法是否安全?
- 从移出对象移动
- 在 2D 阵列板中移动并防止玩家移出板
- 可以将std::getline()与从std::string中移出的字符串一起使用吗
- 是否可以将 std::move 对象移出函数?(C++11).
- 是否应将移出对象保留为"safe"状态?
- 如何将unique_ptr移出矢量<Foo><unique_ptr>?
- 如何使用默认移动构造函数将数据移出范围
- 头文件中定义的多个结构 - 我是否应该将它们移出单独的 h 和 cpp 文件中
- 将具有限制的通用模板移出类定义
- C++ - 无法将 istringstream 定义移出循环