我可以很容易地创建一个模板函数,它接受任意类型的任意容器并对其进行操作
Can I easily make a template function that takes an arbitrary container of an arbitrary type and operates on it?
我正试图得到这样的工作:
// 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
类型?这就是你想要的吗?
相关文章:
- 从函数返回任意简单类型的数据
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 类型别名允许分配任意指针,尽管 int* 是必需的
- 包装任意类型/非类型模板类的模板类
- 使用模板将任意类型参数传递给 C++ 中的函数
- 有没有办法找到任意类类型的直接基类(如果有的话)?
- is_invocable使用任意函数参数类型
- 如何动态执行具有任意参数类型的函数指针
- 创建一个模板函数来读取 hdf5 中的任意数据类型
- 如何根据特定类型任意启用或禁用类方法
- C++类中的任意数据类型
- 如何在任意依赖类型上专门化模板
- 复制构造,然后访问任意POD类型
- C++ iStream 运算符>>期望任意输入类型
- c++模板类;任意容器类型的函数,如何定义它
- 将std::string转换为任意数字类型或std::string的成员函数模板
- 任意算术类型的比较:有人知道实现吗?
- <algorithm> 对任意数据类型使用库
- 如何在同一列表中存储指向任意类类型的方法指针
- 不使用stringstream将char*转换为任意数字类型