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

c++ (g++-4.x) problem with templates

本文关键字:问题 g++-4 c++      更新时间:2023-10-16

我有一个简单的代码:

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来克服这一问题

 typedef TestHelper< ::Test >  Helper;

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

与普通(非模板)类一样,类模板有一个注入的类名(第9条)。注入的类名可以用作模板名类型名当它与模板参数列表一起使用时,用作模板的模板参数,或者用作友类模板声明的详细类型说明符中的最终标识符时,指代类模板本身。否则,它等效于<>中包含的类模板的模板名称,后跟的模板参数

@Ben可能是对的,但这里有一种完全不同的编译方法,它不使用模板作为模板的参数。

template<class Generator> // changed this to a simpler template
class TestHelper {};
template<class Writer>
class Test
{
            typedef TestHelper< typename Test :: Writer >  Helper; // 2nd change
};

我做了两个改动@雨果,也许这就是你想要的,也许这是g++的旧版本所做的?

编译代码很容易,但这并不意味着它会做你认为的事情!