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库中有自动模板参数?


基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31