对可以传递给自动模板参数的内容有限制吗? [英] Are There Restrictions on What can be Passed to auto Template Parameters?

查看:124
本文介绍了对可以传递给自动模板参数的内容有限制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++ 17 我们获得了 auto模板参数.我试图用一个来传递对象,这个问题是:我可以根据算术运算写关系运算符吗?但是由 AndyG的评论指导没有编译的:(

In c++17 we got auto template parameters. I was trying to use one to pass an object in this question: Can I Write Relational Operators in Terms of Arithmetic Operations? But directed by AndyG's comment I found that didn't compile :(

使用模板功能:

template <auto T>
void foo()

我可以作为模板参数传递的内容似乎受到限制.例如,从我的链接问题中可以看出,我似乎无法传递函子:

There seem to be restrictions on what I can pass as a template parameter. For example, as seen in my linked question I cannot seem to pass functors:

foo<plus<int>{}>()

是否存在允许和不允许的清单?

Is there a list somewhere of what is and isn't allowed?

推荐答案

在C ++ 17中,可以在

In C++17, the restriction can be found in [temp.param]/4:

非类型模板参数应具有以下类型之一(可选的cv限定):

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • 整数或枚举类型
  • 指向对象的指针或指向函数的指针,
  • 对对象的左值引用或对函数的左值引用,
  • 成员的指针,
  • std​::​nullptr_­t
  • 包含占位符类型的类型.
  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std​::​nullptr_­t, or
  • a type that contains a placeholder type.

[temp.arg .nontype]/2 :

对于引用或指针类型的非类型模板参数,常量表达式的值不得引用(或对于指针类型,不得为其地址):

For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):

  • 一个子对象
  • 一个临时对象
  • 字符串文字,
  • typeid表达式的结果,或者
  • 预定义的_­_­func_­_变量.
  • a subobject,
  • a temporary object,
  • a string literal,
  • the result of a typeid expression, or
  • a predefined _­_­func_­_­ variable.

您要出错的地方是std::plus<int>不是有效的非类型模板参数.在第一个列表中没有这些东西.

Where you're going wrong is that std::plus<int> is not a valid non-type template parameter. It is none of those things in that first list.

在C ++ 20中,可以用作非类型模板参数的类型种类将大大扩展.我们将能够使用类类型作为非类型模板参数,只要这些类类型满足强结构相等性"的要求.在当前草案中,这是根据公开定义的,默认为operator<=>.在P1185中,目前正在飞行并且可能会被采用,它将稍作更改,以公开方式定义,默认为operator==.

In C++20, the kinds of types you can use as non-type template parameters will be greatly expanded. We will be able to use class types as non-type template parameters, provided those class types satisfy something called "strong structural equality." In the current draft, that is defined in terms of public, defaulted operator<=>. In P1185, currently in flight and likely to be adopted, it will change slightly to be defined in terms of public, defaulted operator==.

但是即使在C ++ 20中,std::plus<int>实际上也没有定义任何比较运算符-因此您仍然不能将其用作非类型模板参数.

But even in C++20, std::plus<int> does not actually define any comparison operators - so you still would not be able to use it as a non-type template parameter.

这篇关于对可以传递给自动模板参数的内容有限制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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