gpt4 book ai didi

c++ - 将编译时已知函数参数转换为 std::integral_constant 的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:18 25 4
gpt4 key购买 nike

昨天我读了一个blog entry关于将编译时已知函数参数从 constexpr 函数转换为类似 std::integral_constant<> 的类型.

一个可能的用法示例是从用户定义的文字转换类型。

考虑以下示例:

constexpr auto convert(int i)
{
return std::integral_constant<int, i>{};
}

void test()
{
// should be std::integral_constant<int, 22>
using type = decltype(convert(22));
}

但很明显,正如预期的那样,Clang 会抛出以下错误:


error: ‘i’ is not a constant expression
return std::integral_constant<int, i>{};
^

上述博客的作者建议使用模板化的用户定义文字来拆分将数字转换为 std::integer_sequence 以将其解析为 int。

但这个建议对我来说似乎没有用。

有没有一种有效的方法可以将编译时已知的函数参数转换为类似 std::integral_constant<> 的类型? ?

最佳答案

函数参数永远不会是编译时常量。虽然在我看来这是 constexpr 的设计缺陷,但事实就是如此。

可能有其他方法可以做你想做的事(宏、模板),但你不能用函数参数来做。

关于c++ - 将编译时已知函数参数转换为 std::integral_constant 的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com