Something like std::integral_constant but with auto template argument in std C++20 library?(像STD::INTEGERAL_CONSTANT,但在STD C++20库中有自动模板参数?)
问题描述
从C++20开始,可以使用auto模板参数实现整型常量:
Try it online!
template <auto Value>
struct integral_constant2
: std::integral_constant<decltype(Value), Value> {};
它可以用来代替有两个模板参数的更冗长的变体std::integral_constant。
确保编写f(std::integral_constant2<123>{});比编写更冗长的f(std::integral_constant<int, 123>{});更容易。更重要的是,如果您有复杂的编译时表达式,您可能不会提前知道类型。
constexpr函数std::make_integral_constant(123)推导出std::integral_constant的模板参数?
推荐答案
不,我不知道有这样的替换。
我认为,鉴于编写自己的提案是多么容易,为这样的提案辩护将是困难的。另一方面,唯一的原因可能是还没有人提出。
主要是出于好奇,并在评论的基础上进行扩展,您可以通过以下方式更进一步:
#include <type_traits>
template <auto Value, template<typename A, A> typename C>
using automized = C< decltype(Value),Value>;
template <auto Value>
using integral_constant = automized<Value,std::integral_constant>;
int main() {
struct S {};
integral_constant<true> c0{};
integral_constant<10> c1{};
integral_constant<S{}> c2{};
}
automized将允许将auto参数转发到获取typename T, T value任何模板。然而,它是相当有限的,因为它只适用于完全接受那些参数的模板,而当类型参数和非类型参数可以混合时,正确处理一般情况是相当困难的。
这篇关于像STD::INTEGERAL_CONSTANT,但在STD C++20库中有自动模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:像STD::INTEGERAL_CONSTANT,但在STD C++20库中有自动模板参数?
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
