为什么 `std::common_type_t<std::ostream &, std::ostream &>` 等于 `std::ostream` 而不是 `std::ostream &`?

Why is `std::common_type_t<std::ostream &, std::ostream &>` equal to `std::ostream` and not `std::ostream &`?

我正在开发一个小型图书馆,我需要做的一件事是让访问者查看一些数据并return结果。

在一些较旧的 C++ 代码中,访问者需要声明一个 typedef return_type。例如,boost::static_visitor 就是这样做的。

在较新的代码中,所有这些访问者都已弃用。在 C++14 中,您通常可以使用 decltype(auto),但我正在尝试使用 std::common_type 之类的东西来做到这一点,以便我可以在 C++11 中做到这一点。

我尝试简单地将 std::common_type 的示例实现反向移植到 C++11 并使用它来计算 return 类型。

然而,在 cppreference.com

上使用 "possible implementation" 时,我得到了一些意想不到的结果
#include <ostream>
#include <type_traits>

// decay_t backport

template <typename T>
using decay_t = typename std::decay<T>::type;

// common_type backport

template <typename T, typename... Ts>
struct common_type;

template <typename T>
struct common_type<T> {
  using type = decay_t<T>;
};

template <typename T1, typename T2>
struct common_type<T1, T2> {
  using type = decay_t<decltype(true ? std::declval<T1>() : std::declval<T2>())>;
};

// TODO: Is this needed?
/*
template <typename T>
struct common_type<T, T> {
  using type = T;
};
*/

template <typename T1, typename T2, typename T3, typename... Ts>
struct common_type<T1, T2, T3, Ts...> {
  using type = typename common_type<typename common_type<T1, T2>::type, T3, Ts...>::type;
};

template <typename T, typename... Ts>
using common_type_t = typename common_type<T, Ts...>::type;

// static_assert(std::is_same<common_type_t<std::ostream &, std::ostream &>, std::ostream &>::value, "This is what I expected!");
static_assert(std::is_same<common_type_t<std::ostream &, std::ostream &>, std::ostream>::value, "Hmm...");

int main() {}

"should"std::common_type_t<std::ostream&, std::ostream&>的结果是什么?不应该是std::ostream &吗?如果不是,那为什么gcc 5.4.0clang 3.8.0都认为是std::ostream

注意:当我在 C++14 中使用 "real" std::common_type_t 时,我仍然得到 std::ostream 而不是 std::ostream &.

是否专门化 std::common_type 以便 std::common_type_t<T, T> 始终是 T 一种有效的方法?它在我的程序中似乎运行良好,但感觉像 hack。

请参阅 this question 了解有关 common_type 历史的相关讨论以及为什么它实际上没有产生参考。

Is specializing std::common_type so that std::common_type_t<T, T> is always T a valid approach?

我假设你的意思是专门化你的实现common_type(因为你不能专门化另一个)。不,这还不够。您可能希望 common_type<Base&, Derived&> 成为 Base&,但该实例化不会通过您的专业化。

您真正想要的是而不是使用decaydecay 在那里的原因是为了删除 declval 在某些情况下提供的令人惊讶的右值引用。但是你想维护左值引用 - 所以只需添加你自己的类型特征:

template <class T>
using common_decay_t = std::conditional_t<
    std::is_lvalue_reference<T>::value,
    T,
    std::remove_reference_t<T>>;

并使用它代替正常的 decay