99网
您的当前位置:首页[C++]C++17怎么判断类型T是std::vector

[C++]C++17怎么判断类型T是std::vector

来源:99网

C++20可以这样判断:

template<class T> concept is_vector = requires(T t)
{
    std::same_as<std::remove_cvref_t<T>, std::vector<typename std::remove_cvref_t<T>::value_type>>;
};

C++11这样判断:

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

template <typename T>
using is_vector_11 = typename is_std_vector<std::remove_cvref_t<T>>::type;

你那种实现方法很怪,是判断一个类型可以隐式转换为vector,而且你的代码中有volatile那一行我这里是编不过的:

// 你自己实现的StlVector我在clang中编不过
static_assert(StlVector<volatile std::vector<int>>);
// 换成我上面写的11就能编过:
static_assert(is_vector_11<volatile std::vector<int>>::value);
// 换成concept也能编过:
static_assert(is_vector<volatile std::vector<int>>);

stackoverflow 上看到的,直接一步到位,判断一个类是不是另一个模板类的特化类型。

template <typename, template <typename...> class>
struct is_specialization: std::false_type {};

template <template <typename...> class Template, typename... Args>
struct is_specialization<Template<Args...>, Template>: std::true_type {};

int main() {
    constexpr bool is_vec = is_specialization<std::vector<int>, std::vector>::value;
    printf("%d\n", is_vec);
}

因篇幅问题不能全部显示,请点此查看更多更全内容