类类型非类型模板参数初始化不编译 [英] Class type non-type template parameter initialization does not compile

查看:54
本文介绍了类类型非类型模板参数初始化不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,以下内容应成为新的C ++ 20标准下的有效代码:

I was under the impression that the following should become valid code under the new C++20 standard:

struct Foo
{
  int a, b;
};

template<Foo>
struct Bar
{};

Bar<{.a=1, .b=2}> bar;

但是,设置了 -std = c ++ 20 gcc 10.2.0 抱怨:无法将'{1,2}'从'将<大括号括起来的初始化程序列表>'设置为'Foo',Clang也无法编译此代码段.有人可以指出为什么它的格式不正确吗?

Yet, gcc 10.2.0, with -std=c++20 set complains: could not convert ‘{1, 2}’ from ‘<brace-enclosed initializer list>’ to ‘Foo’ and Clang cannot compile this snippet either. Can someone point out why it is not well formed?

推荐答案

此模板参数

{.a=1, .b=2}

根据 template-argument <的语法,不允许

/a>仅允许以下构造:

is not allowed according to the grammar for a template-argument which only allows the following constructs:

模板参数:

constant-expression

constant-expression

type-id

id-expression

id-expression

大括号初始化列表不是上述任何构造,它实际上是

A brace-init list is not any of the above constructs, it's actually an initializer and so it cannot be used as a template-argument.

您可以明确说明用作模板参数的对象的类型:

You can be explicit about the type of the object that you use as the template-argument:

Bar<Foo{.a=1, .b=2}> bar;

这将起作用,因为这是一个常量表达式.

and this will work, since this is a constant-expression.

感谢@NicolBolas和@Artyer向我指出这一点.

Thanks to @NicolBolas and @Artyer for pointing this out to me.

这篇关于类类型非类型模板参数初始化不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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