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


- XML Schema 到 C++ 类 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- DoEvents 等效于 C++? 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01