Efficient way to convert a compile time known function argument to a std::integral_constant

蓝咒 提交于 2019-12-24 15:11:05

问题


Yesterday I read a blog entry about converting a compile time known function argument from a constexpr function to a type like std::integral_constant<>.

A possible usage example is to convert types from user defined literals.

Consider the following example:

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));
}

But obviously and as expected Clang throws the following error:

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

The Author of the mentioned blog proposed to use a templated user defined literal to split the number into a std::integer_sequence to parse it into an int.

But this suggestion seems not useable for me.

Is there an efficient way to convert a compile time known function argument into a type like std::integral_constant<>?


回答1:


Function arguments can never be compile-time constants. While this is a design flaw of constexpr in my opinion, it is the way it is.

There might be other ways to do what you want (macros, templates), but you can not do it with function arguments.




回答2:


You need to use a template:

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>());
}

Or(even better) you can use template aliases:

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


来源:https://stackoverflow.com/questions/33055791/efficient-way-to-convert-a-compile-time-known-function-argument-to-a-stdintegr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!