推导用户定义值模板参数(C++2a,P0732R2)

Deducing a user-defined-value template argument (C++2a, P0732R2)

我正在尝试使用带有 -std=c++2a 的 GCC 9.1 获取用户定义的 class 推导 (http://wg21.link/p0732r2) 的模板参数的值。

struct user_type {
   int a;
   constexpr user_type( int a ): a( a ){}
};

template< user_type u > struct value {};

template< user_type u > void f( value< u > arg ){}  

void g(){
  f( value< user_type( 0 ) >() ); // error here
}

编译器资源管理器:https://godbolt.org/z/6v_p_R

我收到错误:

source>:8:30: note:   template argument deduction/substitution failed:
<source>:11:33: note:   couldn't deduce template parameter 'u'
   11 |    f( value< user_type( 0 ) >() );

我是不是做错了什么?我曾期望这样的价值可以扣除。

按照 Nikita 的建议,我在用户类型中添加了 == 和 != 运算符,但这没有任何区别。

struct user_type {
   int a;
   constexpr user_type( int a ): a( a ){}
   constexpr bool operator==( const user_type & arg ) const {
      return a == arg.a;
   }
   constexpr bool operator!=( const user_type & arg ) const {
      return a != arg.a;
   }
};

这应该是错误的:

struct user_type {
   int a;
   constexpr user_type( int a ): a( a ){}
};

template< user_type u > struct value {};

要成为模板非类型参数,需要满足[temp.param]/4:

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

  • a literal type that has strong structural equality ([class.compare.default]),
  • [...]

需要强结构平等的地方,来自[class.compare.default]/3

A type C has strong structural equality if, given a glvalue x of type const C, either:

  • C is a non-class type and [...], or
  • C is a class type with an == operator defined as defaulted in the definition of C, x == x is well-formed when contextually converted to bool, all of C's base class subobjects and non-static data members have strong structural equality, and C has no mutable or volatile subobjects.

关键是我们需要一个默认的 == 类型...而我们没有,所以我们的类型不具有强结构相等性,所以它不能用作模板非类型参数。

但是,gcc doesn't let you 还没有声明这样的运算符,所以您无法解决问题。

这只是新功能的不完整实现。