[英]ADL and friend functions of templated types
我正在嘗試使用模板為我自動生成大量運算符。 它們與以下代碼非常相似,但無法編譯:
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 相同的命名空間中,但我不知道如何解決這個問題。
有人知道我在這里嘗試做的事情是否可行嗎?
像這樣的東西會起作用:
// 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
結構中刪除了朋友聲明,因為它是不必要的。 或者,您可以在A
、 B
類中聲明友元運算符,盡管這可能不是您想要的。
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 需要運算符,則不需要模板。 如果沒有,那么有一些方法可以限制類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.