c – 声明模板函数以接受任何容器,但只接受一个包含类型
发布时间:2020-12-16 10:08:04 所属栏目:百科 来源:网络整理
导读:我想声明一个接受不同STL容器的函数,但它们必须包含特定类的对象(例如,它应该接受std :: vector double和std :: deque double但是没有std :: vector std: :串GT). 我已经找到了模板容器和包含类型的答案,但我试图调整它们以便修复包含的类型是不成功的. 解
我想声明一个接受不同STL容器的函数,但它们必须包含特定类的对象(例如,它应该接受std :: vector< double>和std :: deque< double>但是没有std :: vector< std: :串GT). 我已经找到了模板容器和包含类型的答案,但我试图调整它们以便修复包含的类型是不成功的.
解决方法
您可以使用模板模板参数(无拼写错误)来完成.模板函数的第一个模板参数是具有可变数量模板参数的另一个模板.第二个模板参数是可变参数模板参数.在签名中,然后将第一个模板参数修复为您想要的类型(例如double),让编译器推断出其余部分.
#include <deque> #include <iostream> #include <string> #include <vector> template < template < class ... > class Container,class ... Args > void any_container(Container<double,Args...>) { // print what was deduced std::cout << __PRETTY_FUNCTION__ << 'n'; } int main() { std::vector<double> vd; any_container(vd); std::deque<double> dd; any_container(dd); std::vector<std::string> vs; any_container(vs); // BOOM! } @PasserBy已经暗示了一个不同的解决方案in this comment.您也可以将容器作为模板参数,并在static_assert中查询其value_type,而不是替换失败.这样做的好处是可以放置自定义错误消息. #include <deque> #include <iostream> #include <string> #include <type_traits> #include <vector> template <typename Container> void any_container(Container) { static_assert(std::is_same<typename Container::value_type,double>::value,"BOOM!"); // print what was deduced std::cout << __PRETTY_FUNCTION__ << 'n'; } int main() { std::vector<double> vd; any_container(vd); std::deque<double> dd; any_container(dd); std::vector<std::string> vs; any_container(vs); // BOOM! } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 初识SQLite[二]
- 将博客导入Jekyll – 这个加载错误是什么’需要无法加载此类
- ruby-on-rails – RubyInstaller 2.2.1和Rails – Rake无法
- .net实现微信公众账号接口开发实例代码
- c# – NewtonSoft json转换器“unterminated String,expect
- c# – ArrayList是一个数组还是一个List?
- 通过具有任意函数的非整数因子聚合栅格
- c# – 以^ Bo开头的字符串
- ruby-on-rails – Capistrano和GitHub Private Repo – 权限
- ruby-on-rails – 在Ruby中,应该使用|| =还是定义?记录?