我可以轻松地创建一个模板函数,它接受任意类型的任意容器并对其进行操作吗?

ani*_*nio 3 c++ templates

我正试图让这样的东西起作用:

// 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)

Oli*_*rth 8

你可以这样做:

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)


Mr.*_*bis 6

你可以做 :

template < typename U>
void foo(U& u) 
{
  typename U::value_type blah = *u.begin();
}
Run Code Online (Sandbox Code Playgroud)

  • 你在@OliCharlesworth之前回答.你也应该得到分数. (3认同)

Stu*_*etz 5

试试这个:

#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的版本,因为它更通用!:)

  • 此版本的一个优点是您可以使用T作为返回值或其他参数.在oli和FreakEnums版本中,T超出了它的范围. (2认同)