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

Den*_*ank 1 c++ templates c++14

昨天我读了一篇 关于将编译时已知函数参数从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));
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

但这个建议对我来说似乎无法使用.

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

orl*_*rlp 5

功能参数可以永远是编译时间常数.虽然这是constexpr我认为的设计缺陷,但事实就是如此.

可能有其他方法可以执行您想要的操作(宏,模板),但您无法使用函数参数执行此操作.