我已经花了一上午的时间在这个问题上,但没有任何结果。基本上,我需要一个简单的元编程,它允许我在传递的参数是否是std::vector的情况下分支到不同的专门化。模板的某种is_base_of。有这种东西吗?
std::vector
is_base_of
fwzugrvs1#
在C++11中,你也可以用一种更通用的方式来实现:
#include <type_traits> #include <iostream> #include <vector> #include <list> template<typename Test, template<typename...> class Ref> struct is_specialization : std::false_type {}; template<template<typename...> class Ref, typename... Args> struct is_specialization<Ref<Args...>, Ref>: std::true_type {}; int main() { typedef std::vector<int> vec; typedef int not_vec; std::cout << is_specialization<vec, std::vector>::value << is_specialization<not_vec, std::vector>::value; typedef std::list<int> lst; typedef int not_lst; std::cout << is_specialization<lst, std::list>::value << is_specialization<not_lst, std::list>::value; }
ct2axkht2#
如果您需要一个trait类,这非常简单,您只需要一个通用模板和一个对任何std::vector的专门化:
#include <type_traits> #include <iostream> #include <vector> template<typename> struct is_std_vector : std::false_type {}; template<typename T, typename A> struct is_std_vector<std::vector<T,A>> : std::true_type {}; int main() { typedef std::vector<int> vec; typedef int not_vec; std::cout << is_std_vector<vec>::value << is_std_vector<not_vec>::value; }
mctunoxg3#
不可以,但是你可以重载一个只接受std::vector<T>的模板函数。在这种情况下,编译器会选择最专业的模板。
std::vector<T>
x7yiwoj44#
在C++ 11中,有一个简单的方法来确定T是否为向量:
static_cast(std::is_same<T, std::vector<typename T::value_type>>::value);
u2nhd7ah5#
定义以下两个函数应该有效:
template<class T> bool is_vector(const std::vector<T>& x) {return true;} template<class T> bool is_vector(const T& x) {return false;}
示例:
auto x {std::vector<double> {23, 32, 33}}; auto y {1.2}; std::cout << is_vector(x) std::endl; std::cout << is_vector(y) std::endl;
5条答案
按热度按时间fwzugrvs1#
在C++11中,你也可以用一种更通用的方式来实现:
ct2axkht2#
如果您需要一个trait类,这非常简单,您只需要一个通用模板和一个对任何
std::vector
的专门化:mctunoxg3#
不可以,但是你可以重载一个只接受
std::vector<T>
的模板函数。在这种情况下,编译器会选择最专业的模板。x7yiwoj44#
在C++ 11中,有一个简单的方法来确定T是否为向量:
u2nhd7ah5#
定义以下两个函数应该有效:
示例: