1

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

3
  • How is using type = decltype(convert(22)); more readable than an alias template (or a variable template)? Commented Oct 10, 2015 at 15:53
  • Do you have any reason to doubt the information you got from that blog post, other than wishful thinking? It already explains why this is invalid, and I don't see how an answer here telling you that same thing can improve on that. Commented Oct 10, 2015 at 15:57
  • using type = decltype(convert(22)) was just an example how to extract the type of the given expression. I thought about possibilities to parse the expression convert(22) into a compile time AST expression which could be evaluated from other templates without using macros or user defined literals. Commented Oct 10, 2015 at 16:12

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.