【发布时间】:2016-07-24 17:21:45
【问题描述】:
我想在具有各种组件的结构上定义一个向量空间(即按组件进行加法和标量乘法)。因此,在这个简短的示例中,我为特定结构重载 operator*=,然后在模板中为任何 operator* 使用它。
以下代码编译运行:
#include <assert.h>
struct myfloat3 { float x, y, z; };
myfloat3 operator*=(myfloat3& a, const float b) {
a.x *= b; a.y *= b; a.z *= b;
return a;
}
template<typename Pt>
Pt operator*(const Pt& a, const float b) {
auto prod = a;
prod *= b;
return prod;
}
// template<typename Pt>
// Pt operator*(const float b, const Pt& a) {
// auto prod = a;
// prod *= b;
// return prod;
// }
int main(int argc, char const *argv[]) {
myfloat3 x {1, 2, 3};
assert((x*3.0f).x == 3);
return 0;
}
但如果我取消注释另一个排序的第二个重载float * myfloat3,我会得到
$ g++ -std=c++11 sandbox/overload.cpp
sandbox/overload.cpp:20:4: error: overloaded 'operator*' must have at least one
parameter of class or enumeration type
Pt operator*(const float b, const Pt& a) {
^
sandbox/overload.cpp:30:14: note: in instantiation of function template
specialization 'operator*<float>' requested here
assert((x*3.0f).x == 3);
^
/usr/include/assert.h:93:25: note: expanded from macro 'assert'
(__builtin_expect(!(e), 0) ? __assert_rtn(__func__, __FILE__, __LINE...
^
1 error generated.
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix
但是使用不同的编译器它可以工作:
$ g++ --version
g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2
$ g++ -std=c++11 sandbox/soverload.cpp
有什么想法吗?
【问题讨论】:
-
stackoverflow.com/q/18596412/4326278 是相关的,但请注意接受答案的 cmets。
-
谢谢,当我回到笔记本电脑上时,我会尝试使用这个 SFINA 魔法。
标签: c++ templates operator-overloading