Naios
Naios

Reputation: 1573

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

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<>?

Upvotes: 1

Views: 218

Answers (2)

user4180612
user4180612

Reputation:

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

Upvotes: 3

orlp
orlp

Reputation: 117681

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.

Upvotes: 5

Related Questions