给出以下代码:
struct Zero{};
template<typename T>
Zero operator*(const Zero& zero, const T& other){return Zero();}
struct Identity{};
template<typename T>
T operator*(const T& other, const Identity& id){return T();}
现在,我想像这样使用这段代码:
Zero z;
Identity id;
int i = 5;
z * i; // ok
i * id; // ok
z * id; //error: ambiguity in function resolution
编译器将无法解析最后一行中的运算符,因为这两个函数都可以使用。事实上,在这种情况下,我并不关心使用哪个函数,因为它们具有相同的功能。在这两种情况下,Zero() 都会按预期返回。
我的问题:在这种情况下我该如何表达任何功能都可以使用?
最佳答案
只需再添加一个重载(这不是任何模板):
Zero operator*(const Zero& other, const Identity& id){return Zero();}
关于c++ - 在模板化函数不明确的情况下表达偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347941/