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

标签 c++ templates typename

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

#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/

相关文章:

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

c++ - 没有 std::atomics 的无锁哈希保证在 C++11 中是线程安全的吗?

c++ - 以十六进制生成随机 16 字节数组

c++ - 自定义排序比较函数抛出编译错误

c++ - 使用自制的 `std::priority_queue` 初始化 `std::Compare` 时避免使用模板?

c++ - C++中的 'typename'字

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c++ - 结构中二维数组的动态内存分配

c++ - 替换失败有时是一个错误

c++ - 检测 C++ lambda 是否可以转换为函数指针