gpt4 book ai didi

c++ - 重载运算符的模板 : error: overloaded 'operator*' must have at least one parameter of class or enumeration type

转载 作者:太空宇宙 更新时间:2023-11-04 13:13:33 25 4
gpt4 key购买 nike

我想在具有各种组件的结构上定义一个 vector 空间(即按组件加法和标量乘法)。因此,在这个简短的示例中,我为特定结构重载了 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

有什么想法吗?

最佳答案

使用带有 enable_if 的特征类来控制何时启用模板:

template<typename Pt> struct Is_vector: public std::false_type {};
template<> struct Is_vector<float3>: public std::true_type {};

template<typename Pt>
typename std::enable_if<Is_vector<Pt>::value, Pt>::type
operator*(const Pt& a, const float b) {
auto prod = a;
prod *= b;
return prod;
}

template<typename Pt>
typename std::enable_if<Is_vector<Pt>::value, Pt>::type
operator*(const float b, const Pt& a) {
auto prod = a;
prod *= b;
return prod;
}

参见 https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/enable-ifThrust reduction and overloaded operator-(const float3&, const float3&) won't compile用于解释。

关于c++ - 重载运算符的模板 : error: overloaded 'operator*' must have at least one parameter of class or enumeration type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38554704/

25 4 0