- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在开发一个小型图书馆,我需要做的一件事是让访问者访问一些数据并返回结果。
在一些较旧的 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.0
和 clang 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 thatstd::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/
来自 cppreference : template constexpr std::common_type_t gcd(M m, N n); (since C++17) IIUC,返回正确的类型
我正在开发一个小型图书馆,我需要做的一件事是让访问者访问一些数据并返回结果。 在一些较旧的 C++ 代码中,访问者需要声明一个 typedef return_type .例如,boost::stati
我是一名优秀的程序员,十分优秀!