为什么要指定`std :: declval`以返回引用类型?

时间:2019-10-06 22:03:27

标签: c++ c++17

std::declval<T>()始终返回引用,除非Tvoid。为什么它不仅仅返回您给出的类型?对于C ++ 17通过简化值类别(https://medium.com/@barryrevzin/value-categories-in-c-17-f56ae54bccbe)保证复制省略的规则而言,这一点很重要:

#include <type_traits>

template<typename T>
T declval();

template<typename Enable, typename T, typename... Args>
constexpr bool is_constructible_impl = false;

template<typename T, typename... Args>
constexpr bool is_constructible_impl<std::void_t<decltype(T(declval<Args>()...))>, T, Args...> = true;

template<typename T, typename... Args>
constexpr bool is_constructible = is_constructible_impl<void, T, Args...>;

struct non_movable {
    non_movable() = default;
    non_movable(non_movable const &) = delete;
};

static_assert(!std::is_constructible_v<non_movable, non_movable>);
static_assert(is_constructible<non_movable, non_movable>);

constexpr non_movable x = non_movable();

实时观看:https://godbolt.org/z/zDCDPC

std::declval<T>()是否有理由返回引用?

0 个答案:

没有答案