使用模板参数的value_type [英] Using a templated parameter's value_type
问题描述
如何使用std容器的value_type?
我试着使用它:
How is one supposed to use a std container's value_type?
I tried to use it like so:
#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’
b $ b
我认为这是什么:: value_type是为了?
I thought this was what ::value_type was for?
推荐答案
c> typename :
You have to use typename
:
typename T::value_type pop()
等等。
原因是编译器无法知道T :: value_type是一个成员变量的类型(没有人阻止你定义一个类型 struct X {int value_type;};
并将其传递给模板)。但是没有该函数,代码不能被解析(因为构造的含义取决于某些标识符是否指定类型或变量,例如 T * p
可能是乘法或指针声明)。因此,规则是,可以是类型或变量,并且没有通过用 typename
前缀明确标记为类型的所有内容都被认为是一个变量。
The reason is that the compiler cannot know whether T::value_type is a type of a member variable (nobody hinders you from defining a type struct X { int value_type; };
and pass that to the template). However without that function, the code could not be parsed (because the meaning of constructs changes depending on whether some identifier designates a type or a variable, e.g.T * p
may be a multiplication or a pointer declaration). Therefore the rule is that everything which might be either type or variable and is not explicitly marked as type by prefixing it with typename
is considered a variable.
这篇关于使用模板参数的value_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!