返回模板中没有返回类型声明的值,这是打字错误吗?

return a value without return type declaration in template, is this a typo?

本文关键字:错误 声明 返回类型 返回      更新时间:2023-10-16

我正在看Walter E. Brown的"Modern Template Metaprogramming"讲座。在54:40给出的代码如下

template<class T, T v>
struct integral_constant{
  static constexpr T value = v;
   constexpr  operator T() const noexcept { return value; } // what does this mean?
   constexpr T operator T() const noexcept { return value; }
};
我的问题是这一行是什么意思constexpr operator T() const noexcept { return value; },为什么没有返回类型,但它仍然返回value ?这是打错了吗?

是的,第二个操作符行是错误的,可以完全删除。

像eg这样的类型操作符。operator int()被执行
当对象被强制转换或隐式转换为类型时:

MyClass myObject;
int i = myObject; // here operator int() is used.

自然地,operator int()必须返回int。没有必要也不允许为这样的操作符编写特定的返回类型。在你的例子中,它不是intfloat或任何特定的东西,而是模板类型,但它的思想是一样的。

除了返回类型问题外,第二行操作符再次定义了具有相同参数的相同操作符,不能有多个具有相同名称和参数的函数。

在整个struct之后,缺少一个分号。

修复这些问题后,它编译:http://ideone.com/Hvrex5

第一个不是打字错误。该语法用于提供从类的对象到另一类型的转换。

返回类型T

详情见http://en.cppreference.com/w/cpp/language/cast_operator

consexpr限定符向编译器表明,如果调用成员函数的对象也符合constexpr限定符,则可以在编译时确定成员函数的返回值。

第二个不是合法的语句