【问题标题】:Use tag dispatching to check if type implements size_type使用标签调度检查 type 是否实现 size_type
【发布时间】:2020-03-23 22:49:53
【问题描述】:

我正在寻找一种解决方案来确定特定类型是否实现了 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++14、17 还是 20?
  • StackOverflow 上有很多问题展示了如何使用模板测试成员是否存在。

标签: c++ metaprogramming typetraits


【解决方案1】:
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>);

【讨论】:

    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多