【问题标题】:Express preference in case of ambiguous templated functions在模版化函数模棱两可的情况下表达偏好
【发布时间】:2014-12-07 21:17:32
【问题描述】:

给定以下代码:

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

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

【问题讨论】:

  • 顺便说一句:你可能想看看constexpr

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


【解决方案1】:

只需再添加一个重载(这根本不是模板):

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

【讨论】:

    【解决方案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 {};}
    

    【讨论】:

    • 我喜欢这个答案。虽然它使代码更加复杂,但当我开始使用不同版本的 operator* 时(例如,当模板化“Identity”或“Zero”时)更可取。在上一个答案中,我将不得不复制代码。非常感谢!
    猜你喜欢
    • 2021-10-06
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多