返回模板中没有返回类型声明的值,这是打字错误吗?
return a value without return type declaration in template, is this a typo?
我正在看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
。没有必要也不允许为这样的操作符编写特定的返回类型。在你的例子中,它不是int
或float
或任何特定的东西,而是模板类型,但它的思想是一样的。
除了返回类型问题外,第二行操作符再次定义了具有相同参数的相同操作符,不能有多个具有相同名称和参数的函数。
在整个struct
之后,缺少一个分号。
修复这些问题后,它编译:http://ideone.com/Hvrex5
第一个不是打字错误。该语法用于提供从类的对象到另一类型的转换。
返回类型T
详情见http://en.cppreference.com/w/cpp/language/cast_operator
consexpr
限定符向编译器表明,如果调用成员函数的对象也符合constexpr
限定符,则可以在编译时确定成员函数的返回值。
第二个不是合法的语句
相关文章:
- 错误:未在此范围内声明'reverse'
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 错误:"imread"未在此范围内声明
- 在气泡排序程序中未声明错误功能
- 使用全局声明的向量时,C++双重释放错误/损坏
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- C++ [错误] 声明'char '隐藏参数。什么意思?
- 类中的静态函数给出了错误:声明中的两种或多个数据类型
- 错误:声明冲突 - 指针不能是 int
- 收到 CUDA 错误"声明与以前的"variable_name"不兼容
- 错误:声明不声明
- Visual Studio 2010 链接器错误C++声明我从头文件创建的类时
- Cython 错误:声明不声明任何内容
- 错误"声明非模板函数"C++
- 无效地使用不完整的类型/前向错误声明.可能误用抽象类?(c++)
- 错误:声明冲突.用c++编译c代码
- C++错误:声明中存在显式限定
- else语句(C++)上的错误w/声明
- 初始化const类成员,错误:声明没有声明任何内容