我正试图让这样的东西起作用:
// This method is wrong, won't work, need your help
template < template <typename T> class U >
void foo(U& u)
{
T& blah = *u.begin();
}
int main(int, char**)
{
vector<int> myVec(4, 10);
foo<vector<int> >(myVec); // This is how I want to call it, even better if I can leave the parameters out and just do foo(myVec);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
真的我想要做的是避免以下因为它似乎多余:
template <typename T, typename U>
void foo(U& u)
{
T& blah = *u.begin();
}
int main(int, char**)
{
vector<int> myVec(4, 10);
foo<int, std::vector<int> >(myVec); // first int in parameters is redundant cause I already provide int as arg to vector
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
template <typename U>
void foo(U& u)
{
typedef typename U::value_type T;
T& blah = *u.begin();
}
int main(int, char**)
{
vector<int> myVec(4, 10);
foo(myVec);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
你可以做 :
template < typename U>
void foo(U& u)
{
typename U::value_type blah = *u.begin();
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
#include <vector>
template <template <typename, typename> class Cont, typename T, typename Alloc>
void foo(Cont<T,Alloc>& cont)
{
T& blah = *cont.begin();
}
int main(int, char**)
{
std::vector<int> myVec(4, 10);
foo(myVec);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
原始版本有什么问题,它vector有一个额外的模板参数(分配器类型).此外,您需要指定模板参数,如上所述.
所有这一切都说,我想我更喜欢Oli和FreakEnum的版本,因为它更通用!:)