Andreas Loanjoe
Andreas Loanjoe

Reputation: 2399

Using a "normal" constexpr function argument in a template

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

Upvotes: 0

Views: 139

Answers (1)

bolov
bolov

Reputation: 75854

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

Upvotes: 1

Related Questions