How to know if a type is a specialization of std::vector?

后端 未结 3 1146
借酒劲吻你
借酒劲吻你 2020-11-30 07:44

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 t

相关标签:
3条回答
  • 2020-11-30 08:21

    No, but you can overload with a template function which only accepts std::vector<T>. The compiler will choose the most specialized template in such cases.

    0 讨论(0)
  • 2020-11-30 08:29

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 08:33

    If you need a trait class it's pretty simple, you only need a general template and a specialization over any 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;
    }
    
    0 讨论(0)
提交回复
热议问题