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

时间:2015-10-10 15:45:40

标签: c++ templates c++14

昨天我读了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<>类型的有效方法?

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

您需要使用模板:

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

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

或者(甚至更好)你可以使用模板别名:

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