应该如何使用标准容器的 value_type?
我试着像这样使用它:
#include <vector>
using namespace std;
template <typename T>
class TSContainer {
private:
T container;
public:
void push(T::value_type& item)
{
container.push_back(item);
}
T::value_type pop()
{
T::value_type item = container.pop_front();
return item;
}
};
int main()
{
int i = 1;
TSContainer<vector<int> > tsc;
tsc.push(i);
int v = tsc.pop();
}
但这会导致:
prog.cpp:10: error: ‘T::value_type’ is not a type
prog.cpp:14: error: type ‘T’ is not derived from type ‘TSContainer<T>’
prog.cpp:14: error: expected ‘;’ before ‘pop’
prog.cpp:19: error: expected `;' before ‘}’ token
prog.cpp: In function ‘int main()’:
prog.cpp:25: error: ‘class TSContainer<std::vector<int, std::allocator<int> > >’ has no member named ‘pop’
prog.cpp:25: warning: unused variable ‘v’
我以为这就是 ::value_type 的用途?
原文由 Jonathan Winks 发布,翻译遵循 CC BY-SA 4.0 许可协议
您必须使用
typename
:等等。
原因是编译器无法知道 T::value_type 是否是成员变量的类型(没有人阻止您定义类型
struct X { int value_type; };
并将其传递给模板)。但是,如果没有该函数,则无法解析代码(因为构造的含义会根据某些标识符指定类型或变量而改变,例如T * p
可能是乘法或指针声明)。因此,规则是所有可能是类型或变量且未通过前缀typename
明确标记为类型的所有内容都被视为变量。