在模糊模板函数的情况下表达偏好

时间:2014-12-07 21:17:32

标签: c++ templates overloading operator-keyword specialization

给出以下代码:

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()都将按预期返回。

我的问题:我如何表达,在这种情况下,任何功能都可以使用?

2 个答案:

答案 0 :(得分:3)

再添加一个重载(不是模板):

Zero operator*(const Zero& other, const Identity& id){return Zero();}

答案 1 :(得分:2)

如果TIdentity,请使用SFINAE删除第一个模板:

template<typename T> auto operator*(const Zero& zero, const T& other)
-> typename std::enable_if<!std::is_same<T, Identity>::value, Zero>::value
{return {};}