我整个早上都遇到过这个问题而没有任何结果。 基本上,我需要一个简单的元编程事物,如果传递的参数是一种std :: vector,我可以分支到不同的特化。
模板的某种is_base_of。
这样的事情存在吗?
答案 0 :(得分:17)
如果你需要一个特质课,这很简单,你只需要一个通用模板和一个专业化std::vector
:
#include <type_traits>
#include <iostream>
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;
}
答案 1 :(得分:17)
在C ++ 11中,您也可以采用更通用的方式:
#include <type_traits>
#include <iostream>
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;
}
答案 2 :(得分:4)
不,但您可以使用仅接受std::vector<T>
的模板函数进行重载。在这种情况下,编译器将选择最专业的模板。