const 值作为模板参数 [英] const value as template parameter

查看:32
本文介绍了const 值作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了 gcc 和 clang 的编译错误,所以我认为这段代码是不可能的:

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

编译错误:

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

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

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.

推荐答案

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

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

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

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

你想要的是std::integral_constant:

What you want is std::integral_constant:

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

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

<小时>

正如评论中提到的 Rakete1111return Type>; 也是格式错误的 - 您可能想像我上面那样实例化它.


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.

这篇关于const 值作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆