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

Can I easily make a template function that takes an arbitrary container of an arbitrary type and operates on it?

本文关键字:任意容 类型 任意 操作 创建 很容易 函数 一个 我可以      更新时间:2023-10-16

我正试图得到这样的工作:

// 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;
}

我真正想做的是避免以下内容,因为它看起来是多余的:

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;
}

你可以这样做:

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;
}

你可以这样做:

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

试试这个:

#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;
}

原始版本的问题是vector有一个额外的模板参数(分配器类型)。此外,您需要指定模板参数,就像我上面所做的那样。

说了这么多,我想我更喜欢Oli和FreakEnum的版本,因为它更通用!:)

如果您需要它为不遵循关于value_type类型定义的STL约定的容器类型工作,那么您需要一个标记系统。以下是如何实现这一功能的示例。

template <typename U>
struct foo_tags {
   typedef typename U::value_type value_type;
};
template <typename U>
void foo(U& u)
{
    typedef foo_tags<U>::value_type T;
    T& blah = *u.begin(); 
}
class my_very_special_int_container {
 public:
   int *begin();
};
template <>
struct foo_tags<my_very_special_int_container>
{
    typedef int value_type;
}
int main(int, char**)
{
  vector<int> myVec(4, 10);
  foo(myVec);
  my_very_special_int_container c;
  foo(c);
  return EXIT_SUCCESS;
}

使用std::vector<int>::reference类型?这就是你想要的吗?