【发布时间】: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