c++ - 使用 C++ 模板时的编译错误

标签 c++ templates compiler-errors

<分区>

谁能解释为什么我不能像这样使用 C++ 模板:

template <typename T> class A {
public:
    typedef std::vector<T>::iterator myiterator;

    A(T value)
        :   v(10, value)
    {
    }

    myiterator begin()
    {
        return v.begin();
    }

    myiterator end()
    {
        return v.end();
    }

public:
    std::vector<T> v;
};

int main()
{
    A<int> a(10);

    for (auto i = a.begin(); i != a.end(); ++i)
        std::cout << *i << std::endl;

    return 0;
}

我在声明 myiterator 别名的那一行得到了编译错误;错误是:“缺少';'在标识符“myiterator”之前。

最佳答案

改变

typedef std::vector<T>::iterator myiterator;

typedef typename std::vector<T>::iterator myiterator;

由于您是通过模板化类型( vector )访问类型,因此您需要帮助编译器消除歧义。 vector<T>::iterator可以是静态成员,也可以是类型。如果没有更多关于 T 的知识,编译器就无法确定。使用 typename那里的关键字告诉编译器“将其视为一种类型。”

有关详细信息,请参阅 Where and why do I have to put the "template" and "typename" keywords?

关于c++ - 使用 C++ 模板时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19298878/

相关文章:

ios - Appcelerator - 将新 UDID 添加到配置文件后的 CodeSign 问题

c++ - Gdb 打印 std::map 元素

c++ - "nicer"替代局部变量名称前缀?

c++ - 是否可以在 C++ 的控制台中放大文本

c++ - 在 Cuda 8+ 中使用默认推力自展开 CUDA n 暗淡的相同类型元组创建?

c++ - 调用显式专用类成员模板函数时出现奇怪的编译错误

c++ - 转义到 C 程序中的 C++ 异常行为

c++ - 如何为对象模板声明非常量参数

c++ - 派生类型的自动静态调用

typescript - 在 TypeScript 3.3 中工作的代码在 3.5+ 中被破坏,为什么?