在C++中定义函数模板或类模板时,可以这样写:
template <class T> ...
Run Code Online (Sandbox Code Playgroud)
或者可以这样写:
template <typename T> ...
Run Code Online (Sandbox Code Playgroud)
是否有充分理由偏好一个而不是另一个?
我接受了最受欢迎(也很有趣)的答案,但真正的答案似乎是"不,没有理由偏爱另一个."
typename.class.但是,请注意,在模板模板参数的情况下,需要使用class而不是typename.请参阅下面的user1428839的答案.(但这个特殊情况不是偏好问题,而是语言的要求.)(这也会改变typename)
如何使用std容器的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();
}
Run Code Online (Sandbox Code Playgroud)
但这会导致:
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 ‘}’ …Run Code Online (Sandbox Code Playgroud)