0

Let's say I have this function:

constexpr void foo(size_t x)
{ }

And this template:

template<size_t X>
class bar;

Would it be possible to instantiate an instance of template bar with the constexpr size_t x inside the foo function if I know that I will always constexpr evaluate that function (C++17)?

1 Answer 1

1

If I understand you correctly you want this:

constexpr void foo(size_t x)
{
    bar<x> b{};
}

This is not possible because a constexpr function can be evaluated at runtime, in which case the argument x is not a compile time constant.

What you need to do is make the argument a template argument instead:

template <size_t X>
constexpr void foo()
{
    bar<x> b{};
}

// call it like this:
auto test()
{
     foo<24>();
}
Sign up to request clarification or add additional context in comments.

6 Comments

That is not possible unfortunately because im calling the foo function from another constexpr function, which has it as a normal parameter.
@AndreasLoanjoe and what is the problem that prevents you to call foo like this?
I got the value passed into a constexpr function by value not as template parameter before I want to call foo. Lets say the test function above is also a constexpr function and got size_t as argument how would you do it then.
@AndreasLoanjoe you cannot use a function parameter for the reasons I told. You need to apply the same treatment up the call stack, i.e. make the x template argument all the way.
:( Will this change with constexpr bang functions or consteval in 20?
|

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.