gpt4 book ai didi

c++ - 为什么 `std::common_type_t` 等于 `std::ostream` 而不是 `std::ostream &` ?

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:17 29 4
gpt4 key购买 nike

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

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

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

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

但是,在 cppreference.com 上使用“可能的实现”时,我得到了一些意想不到的结果。

#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() {}

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

注意:当我使用“真实的”std::common_type_t在 C++14 中,我仍然得到 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& ,但该实例化不会通过您的特化。

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

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

并使用它代替普通的 decay .

关于c++ - 为什么 `std::common_type_t<std::ostream &, std::ostream &>` 等于 `std::ostream` 而不是 `std::ostream &` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38704952/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com