使用标签分派来检查类型是否实现了size_type

问题描述 投票:0回答:1

我正在寻找一种解决方案,以找出特定类型是否实现了size_type。目前为止...

struct foo { 
using size_type = int; 
};

template<typename T> 
struct check_size_type {
    static constexpr bool value = true; // something else needs to go here
};  


template<typename T> 
constexpr bool has_size_type_t = check_size_type<T>::value;

int main(){
    static_assert(!has_size_type_t<int>);
    static_assert(has_size_type_t<std::vector<int>>);
    static_assert(has_size_type_t<foo>);  
}
c++ metaprogramming typetraits
1个回答
4
投票
template<class T, class=void> 
struct has_size_type : std::false_type { };

template<class T>
struct has_size_type<T, std::void_t<typename T::size_type>> : std::true_type { };

template<class T>
constexpr auto has_size_type_v = has_size_type<T>::value;

static_assert(!has_size_type_v<int>);
static_assert(has_size_type_v<std::vector<int>>);
static_assert(has_size_type_v<foo>);
© www.soinside.com 2019 - 2024. All rights reserved.