我编写了我的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(?
UPD:
std::common_type_t<Mother, Father, Granny>
不起作用。常用类型的搜索方式是什么?
当将common_type
应用于三个或多个模板参数时,common_type<T1, T2, R...>::type
被定义为common_type_t<C, R...>
,其中C是common_type_t<T1, T2>
。如果T1和T2没有共同的类型,则type
typedef不存在。
这意味着common_type
被定义为从左到右处理其参数,并且它可以在O(n(中完成。这也意味着重新排列论点的顺序可能会导致不同的结果。
在您自己的实现中,您从右向左工作,这就是为什么您会得到不同的结果。