我有这个简单的代码:
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/