【问题标题】:const value as template parameterconst 值作为模板参数
【发布时间】:2017-04-27 13:34:48
【问题描述】:

我刚遇到 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 不是编译时值,您可能会使用来自命令行参数的值调用该 lambda。
  • 如果一个变量是const,它并不一定意味着它在编译时是已知的(正如模板参数所需要的那样)。想象一下这样的例子:int a; std::cin &gt;&gt; a; const int b = a;bconst,但它的值在编译时是未知的。

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


【解决方案1】:

size 是一个 const 值,应该能够适合作为模板参数号吗?

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

你要的是std::integral_constant:

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

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

正如 cmets 中提到的 Rakete1111 一样,return Type&lt;Foo&lt;size&gt;&gt;; 行也是格式错误的 - 您可能想像我在上面所做的那样实例化它。

【讨论】:

  • 您可能想要添加 Type&lt;Foo&lt;size&gt;&gt; 是一种类型,因此您无法返回它。你必须创建它的一个实例,或者使用::type
  • 哦,对了,对不起,我把它从 hana::type_c 改了,忘了初始化。谢谢:)
猜你喜欢
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 2021-09-02
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
相关资源
最近更新 更多