我更喜欢在单独的文件中编写类和函数模板的定义,该文件会自动包含在“public” header 之后。然而,我遇到了一个有趣的案例,看起来我无法做到这一点。
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
int main()
{
Type a;
Type b;
a == b;
}
是否可以单独编写适用于任何 T
和 U
的 operator==
定义?
最佳答案
对于特定专业,是的:
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
int x = 42;
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
bool operator ==(const Type& lhs, const Type& rhs) {
return lhs.x == rhs.x;
}
int main()
{
Type a;
Type b;
a == b;
}
在您的示例中,模板的每个特化都与一个非模板函数交友,该函数将该特定特化作为参数。您可以在类中定义此函数(然后每次实例化模板时都会将其删除),或者您可以在类外定义它 - 但随后您必须为您使用的每个特化定义一个函数。
关于c++ - 内部类模板的非成员运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919785/