c++ - const 值作为模板参数

标签 c++ templates metaprogramming template-meta-programming

我刚刚遇到了 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 值,应该能够适合作为模板参数,不是吗?我已经使用了一些静态 const 值作为模板参数,但似乎不支持这种情况。

最佳答案

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

不,const值不一定在编译时已知(即它们不是常量表达式)。

你想要的是 std::integral_constant :

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

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

Rakete1111评论中提到,行 return Type<Foo<size>>;也是格式错误的 - 您可能想像我上面那样实例化它。

关于c++ - const 值作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659475/

相关文章:

C++模板实例化

ruby - 制作方法的方法 : Easy Ruby Metaprogramming

c++ - 为什么类型推导不能按预期工作?

C++ meta-splat 函数

c++ - 在 C 中是否有一组标准的库用于动态字符串、列表和字典?

c++ - 使用 C++ boost 库如何创建两个圆并将它们添加到 boost R 树中?

c++ - OpenGL 围绕相机移动场景

c++ - 用户自定义转换的第二个标准转换顺序

c++ - 无限模板递归,因为仅使用 gcc 没有 bool 表达式优化

c++ - 如何初始化模板方法中使用的静态类成员?