c++ (g++-4.x) 模板问题

标签 c++ templates g++

我有这个简单的代码:

template<template <class> class Generator>
class TestHelper {};

template<class Writer>
class Test
{
    typedef TestHelper< Test >  Helper;  
};

它在最新的 g++ 版本上运行良好,但在 4.4 或 4.5 中,我收到此错误:

test.cpp:7: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class Generator> class TestHelper' 
test.cpp:7: error:   expected a class template, got 'Test<Writer>'

我做错了什么?

最佳答案

这是因为在类的主体内 Test<Writer> , 命名 Test不提供模板参数会自动采用相同的参数(例如 Writer )。

例如,这允许您将复制构造函数编写为:

Test(const Test&);

代替

Test::Test(const Test<Writer>&);

您可以通过排位赛 Test 来克服这个问题及其 namespace ,例如

 typedef TestHelper< ::Test >  Helper;

注意:正如 Tomalek 所建议的,原始用法在 C++0x 中有效。这是标准的相关段落(强调我的),来自第 14.6.1 节([temp.local]):

Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.

关于c++ (g++-4.x) 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170867/

相关文章:

c++ - 在 V8 中,为什么 Isolate::GetCurrent() 返回 NULL?

c++ - 错误 : expected primary-expression before X token

angularjs - Node.js 使用什么模板引擎

c++ - 转换 int 并将其与 char* 连接

gcc - 从 GCC 切换到 Clang 的常见问题是什么?

c++ - 部分模板特化 - 成员特化

c++ - 在 Visual Studio 2005 中的取消引用指针的地址上设置数据断点

c++ - std::begin - 类型特征中不考虑用户定义的重载

c++ - 模板值特化

c++ - 链接器未在目标文件中找到现有引用