这个话题有很多相关问题,但我仍然对以下案例感到困惑:
#include <iostream>
#include <utility>
struct A {};
struct B { void operator + (const B& /* other */) {} };
struct C { C operator + (const C& /* other */) {return *this;} };
struct D { D& operator + (const D& /* other */) {return *this;} };
template <typename T, typename = void>
struct has_p_op : std::false_type {};
template <typename T>
struct has_p_op<T, decltype(std::declval<T>() + std::declval<T>())> : std::true_type {};
int main()
{
constexpr bool a = has_p_op<A>::value; // false
constexpr bool b = has_p_op<B>::value; // true
constexpr bool c = has_p_op<C>::value; // false
constexpr bool d = has_p_op<D>::value; // false
std::cout << a << b << c << d << std::endl;
}
为什么
c
和 d
不都是 true
?
缺少返回
void
类型。
v1:
template <typename T>
struct has_p_op<T, decltype(std::declval<T>() + std::declval<T>(), void())> : std::true_type {};
v2:
template <typename T>
struct has_p_op<T, std::void_t<decltype(std::declval<T>() + std::declval<T>())>> : std::true_type {};