【发布时间】:2015-01-08 16:30:48
【问题描述】:
g++ 4.9.0 -O2 -std=c++11
template<class T>
struct vec3 {
T x, y, z;
vec3() = default;
vec3(const vec3<T> &other) = default;
vec3(T xx, T yy, T zz) { x = xx; y = yy; z = zz; }
vec3<T> operator-(const vec3<T> &other) {
return vec3<T>{ x - other.x, y - other.y, z - other.z };
}
};
int main() {
vec3<char> pos{ 0, 0, 0 };
vec3<char> newPos{ 0, 0, 0 };
auto p = pos - newPos;
return 0;
}
我收到警告:
!!warning: narrowing conversion of ‘(((int)((vec3<char>*)this)->vec3<char>::x) - ((int)other.vec3<char>::x))’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
但是,如果我在 operator- 函数中使用 (...) insted 或 {...} 执行此操作,则警告会消失。为什么?
【问题讨论】:
-
看看这个GCC bug report的讨论,尤其是Jonathan Wakely's response
-
{}捕获缩小转换(使代码格式错误)。()没有。或者你在问为什么它在缩小? -
是的,为什么变窄了?
标签: c++ templates c++11 narrowing