【发布时间】:2021-12-23 07:30:57
【问题描述】:
我在想如果一个类包含一个类型,我可以测试(使用 C++14),我可以这样做:
#include <type_traits>
struct X {
using some_type = int;
};
struct Y {};
template <typename T, typename = void>
struct has_some_type : std::false_type {};
template <typename C>
struct has_some_type<C, typename C::some_type> : std::true_type {};
static_assert(has_some_type<X>::value); // unexpectedly fails
static_assert(has_some_type<Y>::value); // correctly fails
但是static_assert 失败了,这让我很吃惊,因为检查成员函数会以类似的方式工作。
#include <type_traits>
struct X {
void some_function();
};
struct Y {};
template <typename T, typename = void>
struct has_some_function : std::false_type {};
template <typename C>
struct has_some_function<C, decltype(std::declval<C>().some_function())> : std::true_type {};
static_assert(has_some_function<X>::value); // correctly succeeds
static_assert(has_some_function<Y>::value); // correctly fails
为什么这不起作用,我将如何测试一个类是否有类型?
【问题讨论】:
标签: c++ c++14 template-meta-programming sfinae typetraits