其他分享
首页 > 其他分享> > c – 可以传递给自动模板参数的内容是否有限制?

c – 可以传递给自动模板参数的内容是否有限制?

作者:互联网

参见英文答案 > Non-type template parameters                                    4个
我们得到auto template parameters.我试图用一个来传递一个对象在这个问题:Can I Write Relational Operators in Terms of Arithmetic Operations?但导演AndyG’s comment我发现没有编译:(

给定模板功能:

template <auto T>
void foo()

对于我可以作为模板参数传递的内容似乎存在限制.例如,正如在我的链接问题中看到的,我似乎无法通过仿函数:

foo<plus<int>{}>()

有什么是允许的和不允许的列表吗?

解决方法:

在C 17中,限制可以在[temp.param]/4中找到:

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

  • 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):

  • a subobject,
  • a temporary object,
  • a string literal,
  • the result of a typeid expression, or
  • a predefined _­_­func_­_­ variable.

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

在C 20中,可以大大扩展可用作非类型模板参数的类型.我们将能够使用类类型作为非类型模板参数,前提是这些类类型满足称为“强结构相等”的东西.在当前的草案中,这是根据公共的,默认的操作符< =>来定义的.在P1185中,目前正在飞行并且可能被采用,它将略有变化,以公共,默认操作符==来定义.

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

标签:c,templates,auto,c17,parameters,c++17
来源: https://codeday.me/bug/20190827/1745594.html