const值作为模板参数

const value as template parameter

本文关键字:参数 const      更新时间:2023-10-16

我只是遇到了GCC和Clang的编译错误,因此我认为此代码是不可能的:

template < typename T >
struct Type {
  using type = T;
};
template < int size = 1024 >
struct Foo {};
constexpr auto test_ = [] (const int size) {
  return Type<Foo<size>>;
};

编译错误:

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

问题是为什么?size是const值,应该能够作为模板参数否拟合吗?我已经使用了一些静态常量值作为模板参数,但是似乎不支持这种情况。

size是一个const值,应该能够作为模板参数no?

拟合

no,const值不一定在Compile time 上知道(即。

您想要的是std::integral_constant

constexpr auto test_ = [] (auto size) 
{
    return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});

正如评论中提到的rakete1111所述, return Type<Foo<size>>;行也不明显 - 您可能想像我上面一样对其进行实例化。