`typedef typename Foo <T> :: Bar Bar'的模板声明

ger*_*nte 23 c++ templates typedef typename

我在声明模板类型时遇到了很大困难,如下所示.

#include <cstdlib>
#include <iostream>

using namespace std;


template <class T>
class Foo
{
 typedef T Bar;
};

template <class T>
typedef typename Foo<T>::Bar Bar;




int main(int argc, char *argv[])
{

    Bar bar;

    Foo<int> foo;


    system("PAUSE");
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

我收到错误

template declaration of `typedef typename Foo<T>::Bar Bar' 
Run Code Online (Sandbox Code Playgroud)

关于线

template <class T>
typedef typename Foo<T>::Bar Bar;
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我想避免在我的代码中写入typename Foo :: Bar.

我究竟做错了什么?

Ker*_* SB 34

typedefC++中的声明不能是模板.但是,C++ 11使用using声明添加了另一种语法,以允许参数化类型别名:

template <typename T>
using Bar = typename Foo<T>::Bar;
Run Code Online (Sandbox Code Playgroud)

现在你可以使用:

Bar<int> x;   // is a Foo<int>::Bar
Run Code Online (Sandbox Code Playgroud)

  • @geraldCelente:我认为这不重要或任何人都不高兴 - 选择你认为最有用的答案:-)(或者掷硬币.) (2认同)

Pra*_*ian 8

typedef不能是模板.这正是C++ 11发明别名模板的原因.尝试

template <class T>
using Bar = typename Foo<T>::Bar;
Run Code Online (Sandbox Code Playgroud)


Die*_*ühl 8

你不能typedef是一个模板.但是,您可以使用别名模板.下面的代码演示了使用并修复了一些其他问题:

template <class T>
class Foo
{
public:
    typedef T Bar;
};

template <class T>
using Bar =  typename Foo<T>::Bar;

int main(int argc, char *argv[])
{
    Bar<int> bar;
    Foo<int> foo;
}
Run Code Online (Sandbox Code Playgroud)