c++ - 类模板特化与模板

标签 c++ templates

我有一个类模板 name 来检测类型名称。它适用于简单类型,例如 intfloat。但是,对于某些模板类型,如 std:pair,当我尝试定义其静态成员变量时,编译器 (VS2013) 会在该行报告错误。

#include <cassert>
#include <memory>

using namespace std;

template<class T> struct name{ static const char* value; };

template<class T> const char* name<T>::value = "unknown";
template<> const char* name<int>::value = "int";
template<> const char* name<float>::value = "float";
template<class T1, class T2> const char* name<pair<T1, T2> >::value = "pair"; //compilation error

void main()
{
    assert(name<int>::value == "int");
    assert(name<float>::value == "float");
    assert(name<double>::value == "unknown");
    assert((name<pair<int, char> >::value) == "pair");
}

如果我用以下四行替换该行,程序将按预期工作。

template<class T1, class T2> struct name < pair<T1, T2> > {
    static const char* value;
};
template<class T1, class T2> const char* name<pair<T1, T2> >::value = "pair";

但是由于一些重复的代码,这种方式看起来很难看。有什么办法可以走走吗?

已更新以修复一些明显的标准合规性问题。

最佳答案

首先:template<> 必须引入任何显式特化.尽量保持符合标准。

But this way looks ugly due to some duplicate code. Is there any way to walk around?

没有。非显式特化的成员定义中的参数和实参列表必须匹配主模板或其部分特化之一的列表,并且它对应于其列表匹配的模板成员。 [temp.class.spec.mfunc]:

The template parameter list of a member of a class template partial specialization shall match the template parameter list of the class template partial specialization. The template argument list of a member of a class template partial specialization shall match the template argument list of the class template partial specialization.

所以你必须部分特化模板。不过,您可以为此使用宏:

#define REM_PAR(...) __VA_ARGS__
#define PART_SPEC(string, params, ...) \
    template<REM_PAR params> struct name <__VA_ARGS__ > \
    {  static const char* value; }; \
    \
    template<REM_PAR params> const char* name<__VA_ARGS__>::value = string;

PART_SPEC("pair", (class T, class U), pair<T,U>)

关于c++ - 类模板特化与模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26440493/

相关文章:

c++ - 通过模板或纯虚拟基类继承进行动态类型文件访问?

C++模板题

C++:预期的构造函数、析构函数或类型转换

c++ - c++ 主要用于哪个领域?

python - 在 django 中启用应用程序模板的覆盖?

c++ - 未处理的异常 DirectX11.1 渲染 2D 图形

c++ - 时间序列与序列术语

c++ - VS 2013 模板不编译

c++ - 我应该在哪里包含 <string>?

c++ - 为什么三元运算符会阻止返回值优化?