【问题标题】:ADL and friend functions of templated types模板类型的 ADL 和友元函数
【发布时间】:2020-07-22 21:53:45
【问题描述】:

我正在尝试使用模板为我自动生成大量运算符。它们与以下代码非常相似,但无法编译:

struct A
{
    int value = 1;
};

struct B
{
    int value = 2;
};  

template<typename ParamA, typename ParamB>
struct C
{
    C(int v) : value(v) {}
    
    friend C operator+(const ParamA& a, const ParamB& b)
    {
        return C(a.value + b.value);
    }
    
    int value;
};

int main()
{
    C<A, B> c = A() + B();
}

错误:

 In function 'int main()':
26:21: error: no match for 'operator+' (operand types are 'A' and 'B')
26:13: warning: unused variable 'c' [-Wunused-variable]

为什么 Argument Dependent Lookup 找不到 A 和 B 的 operator+?我认为这可能是因为它既不在全局命名空间中,也不与 A 或 B 相同的命名空间,但我不确定如何解决。

有人知道我在这里尝试做的事情是否可行吗?

【问题讨论】:

  • 你能让operator+成为一个免费的(模板化的)函数吗?

标签: c++ c++11 templates friend argument-dependent-lookup


【解决方案1】:

这样的事情会起作用:

// Struct definitions for A & B ...

struct C
{
    C(int v) : value(v) {}    
    int value;
};

template <typename ParamA, typename ParamB>
C operator+(const ParamA& a, const ParamB& b)
{
        return C(a.value + b.value);
}

我从 C 结构中删除了朋友声明,因为它是不必要的。或者,您可以在 AB 类中声明友元运算符,尽管这可能不是您想要的。

struct C;

struct A
{
    int value = 1;

    template <typename paramA, typename paramB>
    friend C operator+(paramA a, paramB b);
};

struct B
{
    int value = 2;
    template <typename paramA, typename paramB>
    friend C operator+(paramA a, paramB b);
};  

// Struct definition for C
...
// Define templated operator+ function
...

正如@Dani 所指出的,将operator+ 定义为完全通用并不理想。如果仅类型 A 和 B 需要运算符,则不需要模板。如果没有,那么有一些方法可以限制类型。

【讨论】:

  • 使用接受所有内容的模板覆盖运算符是个坏主意。
  • 感谢@Mansoor 的帮助,我非常感谢。我可能会使用你提供的东西。您能否详细说明为什么我的版本不起作用?
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 2015-03-12
  • 2011-07-15
  • 1970-01-01
  • 2016-10-19
  • 2013-09-18
  • 1970-01-01
相关资源
最近更新 更多