c++ - std::common_type 的复杂度是多少?
问题描述
我写了我的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>
不起作用。以何种方式搜索常用类型?
解决方案
当应用于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) 中完成。这也意味着重新排列参数的顺序可能会导致不同的结果。
在您自己的实现中,您从右到左工作,这就是您得到不同结果的原因。
推荐阅读
- javascript - 如何以角度实现队列?
- javascript - 如何向我的 Electron 应用程序添加自定义 chrome 扩展?
- python - BeautifoulSoup4 从源代码中提取标题
- c# - 在菜单中隐藏多余的 ToolStripSeparator
- javascript - 为什么在ajax之后jquery removeClass to button仍然可以正常工作?
- swift - 使用 Decodable 通过 Firestore 获取对象和文档 ID
- r - ggplot中的年度超标概率标度
- google-sheets - 根据另一个工作表中的范围创建列表
- mysql - 有什么不同?
- r - 根据单元格值使用 kableExtra 为行着色