Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ T::iterator出错,其中模板参数T可能是vector<;int>;或列表<;int>;_C++_Templates_Stl_Repr - Fatal编程技术网

C++ T::iterator出错,其中模板参数T可能是vector<;int>;或列表<;int>;

C++ T::iterator出错,其中模板参数T可能是vector<;int>;或列表<;int>;,c++,templates,stl,repr,C++,Templates,Stl,Repr,我正在尝试编写一个函数来打印常见STL容器(向量、列表等)的表示形式。我给函数一个模板参数T,例如,它可能表示向量。我在获取T类型的迭代器时遇到问题 vector<int> v(10, 0); repr< vector<int> >(v); 向量v(10,0); repr(v); 模板 无效报告(施工T&v) { cout您需要typename告诉编译器,::迭代器应该是一个类型。编译器不知道它是一个类型,因为在您实例化模板之前,它不知道t是什么。例如,

我正在尝试编写一个函数来打印常见STL容器(向量、列表等)的表示形式。我给函数一个模板参数T,例如,它可能表示向量。我在获取T类型的迭代器时遇到问题

vector<int> v(10, 0);
repr< vector<int> >(v);
向量v(10,0); repr(v);

模板
无效报告(施工T&v)
{

cout您需要
typename
告诉编译器,
::迭代器
应该是一个类型。编译器不知道它是一个类型,因为在您实例化模板之前,它不知道t是什么。例如,它还可能引用某个静态数据成员。这是您的第一个错误


您的第二个错误是
v
是对-const的引用。因此,您必须使用
::const\u迭代器
。您不能向常量容器请求非常量迭代器。

t::迭代器i;
更改为
类型名t::const\u迭代器i;
,因为
:迭代器
类型为
T
v
常数&

在限定的依赖类型之前,需要
typename
。 没有<代码>类型名< /C>,有C++解析规则,说明有条件的依赖名称应该被解析为<代码>非类型< /代码>,即使它导致语法错误。
typename
声明应将后面的名称视为类型。否则,名称将被解释为指向非类型。

是否也发布“更神秘”的错误消息?顺便说一句,您可能需要替换v.end()-1与非RandomAccess迭代器也支持的其他内容。这并不是说编译器不知道什么是
::iterator
,但标准要求它将其解释为非类型,因为它很好地放在错误消息中:“dependent name”
T::iterator
“被解析为非类型,但实例化会生成一个类型“@visitor:使用正确的两阶段实现(读取“not MSVC”),编译器无法知道第一个过程中的
iterator
,因为模板参数尚未设置。例如,请参见第6项和第7项。
template <typename T>
void repr(const T & v)
{
    cout << "[";
    if (!v.empty())
    {
        cout << ' ';
        T::iterator i;
        for (i = v.begin(); 
             i != v.end()-1;
             ++i)
        {
            cout << *i << ", ";
        }
        cout << *(++i) << ' ';
    }
    cout << "]\n";
}
brett@brett-laptop:~/Desktop/stl$ g++ -Wall main.cpp
main.cpp: In function ‘void repr(const T&)’:
main.cpp:13: error: expected ‘;’ before ‘i’
main.cpp:14: error: ‘i’ was not declared in this scope
main.cpp: In function ‘void repr(const T&) [with T = std::vector<int, std::allocator<int> >]’:
main.cpp:33:   instantiated from here
main.cpp:13: error: dependent-name ‘T::iterator’ is parsed as a non-type, but instantiation yields a type
main.cpp:13: note: say ‘typename T::iterator’ if a type is meant
template <typename T>
void repr(const T & v)
{
    cout << "[";
    if (!v.empty())
    {
        cout << ' ';
        typename T::const_iterator i;
        for (i = v.begin(); 
             i != v.end();
             ++i)
        {
            if (i != v.begin())
            {
                cout << ", ";
            }
            cout << *i;
        }
        cout << ' ';
    }
    cout << "]\n";
}