Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const value as template parameter

I just run into a compile error from both gcc and clang, so I assume this code is not possible :

template < typename T >
struct Type {

  using type = T;
};

template < int size = 1024 >
struct Foo {};

constexpr auto test_ = [] (const int size) {

  return Type<Foo<size>>;
};

Compile error :

test.cpp:12:19: error: non-type template argument is not a constant expression
  return Type<Foo<size>>;
                  ^
1 error generated.

The question is why? size is a const value and should be able to fit as a template parameter no? I already used some static const value as template parameter, but seems this case is not supported.

like image 952
Mathieu Van Nevel Avatar asked Jun 15 '26 22:06

Mathieu Van Nevel


1 Answers

size is a const value and should be able to fit as a template parameter no?

No, const values are not necessarily known at compile-time (i.e. they're not constant expressions).

What you want is std::integral_constant:

constexpr auto test_ = [] (auto size) 
{
    return Type<Foo<size>>{};
};

test_(std::integral_constant<int, 100>{});

As Rakete1111 mentioned in the comments, the line return Type<Foo<size>>; is also ill-formed - you probably wanted to instantiate it as I did above.

like image 159
Vittorio Romeo Avatar answered Jun 17 '26 12:06

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!