如何知道类型是否是 std::vector 的特化?

我整个上午都在解决这个问题,但没有任何结果.基本上,我需要一个简单的元编程东西,如果传递的参数是一种 std::vector 或不是,它允许我分支到不同的专业化.

I've been on this problem all morning with no result whatsoever. Basically, I need a simple metaprogramming thing that allows me to branch to different specializations if the parameter passed is a kind of std::vector or not.

某种用于模板的is_base_of.

这种东西存在吗?

推荐答案

在 C++11 中,您也可以采用更通用的方式:

In C++11 you can also do it in a more generic way:

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

相关文章