昨天我读了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/

10-12 00:26
查看更多