检查类型重载给定的运算符

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

这个话题有很多相关问题,但我仍然对以下案例感到困惑:

#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

c++ c++17 sfinae
1个回答
0
投票

缺少返回

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 {};
© www.soinside.com 2019 - 2024. All rights reserved.