【问题标题】:What is complexity of std::common_type?std::common_type 的复杂度是多少?
【发布时间】: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&lt;Granny, Mother, Father&gt;::type 不会编译,但 std::common_type_t&lt;Granny, Mother, Father&gt; 将返回 Granny 类型。

当 n 是提议的类型计数时,std::common_type 是否适用于 O(n!)(是的,我知道它适用于编译时)?

或者可能是 O(n^2)?

更新:

std::common_type_t&lt;Mother, Father, Granny&gt; 不起作用。常用类型是通过什么方式搜索的?

【问题讨论】:

  • 哪个编译器?
  • @tobias,我对 clang 和 g++ 很感兴趣。
  • 你试过std::common_type&lt;Mother, Father, Granny&gt;吗?成功了吗?
  • @n.1.8e9-where's-my-sharem.,嗯。它不起作用。
  • common_type 被定义为从左到右工作。您的版本从右到左运行,这就是它给出不同结果的原因。

标签: c++ metaprogramming typetraits


【解决方案1】:

common_type 应用于三个或更多模板参数时,common_type&lt;T1, T2, R...&gt;::type 定义为common_type_t&lt;C, R...&gt;,其中 C 为common_type_t&lt;T1, T2&gt;。如果 T1 和 T2 没有共同的类型,则 type typedef 不存在。

这意味着common_type 被定义为从左到右处理其参数,并且可以在 O(n) 中完成。这也意味着重新排列参数的顺序可能会导致不同的结果。

在您自己的实现中,您从右到左工作,这就是您得到不同结果的原因。

【讨论】:

    最近更新 更多