【发布时间】:2023-11-22 03:27:02
【问题描述】:
我写了我的std::common_type 实现:
template <typename Head, typename... Tail>
struct my_common_type {
using type = typename my_common_type<Head, typename my_common_type<Tail...>::type>::type;
};
template <typename T, typename U>
struct my_common_type<T, U> {
using type = std::remove_reference_t<decltype(true ? declval<T>() : declval<U>())>;
};
知道这个元函数返回的类型来自建议,在这种情况下我们可以将其他类型转换为我的实现将不起作用:
struct Granny {};
struct Mother : Granny {};
struct Father : Granny {};
my_common_type<Granny, Mother, Father>::type 不会编译,但 std::common_type_t<Granny, Mother, Father> 将返回 Granny 类型。
当 n 是提议的类型计数时,std::common_type 是否适用于 O(n!)(是的,我知道它适用于编译时)?
或者可能是 O(n^2)?
更新:
std::common_type_t<Mother, Father, Granny> 不起作用。常用类型是通过什么方式搜索的?
【问题讨论】:
-
哪个编译器?
-
@tobias,我对 clang 和 g++ 很感兴趣。
-
你试过
std::common_type<Mother, Father, Granny>吗?成功了吗? -
@n.1.8e9-where's-my-sharem.,嗯。它不起作用。
-
common_type被定义为从左到右工作。您的版本从右到左运行,这就是它给出不同结果的原因。
标签: c++ metaprogramming typetraits