问题是我们被赋予了三个类:我们可以将变量公开。问题中没有提到,我们得到了需要完成的代码块,我们被允许选择类的访问说明符。默认情况下它是私有的。
class A{
int a,b;
};
class B{
int c,d,e;
};
class C{
int f,g;
};
我们需要重载 (>>) 提取和 (<<) insertion operator , such that they will be valid for all the three classes.
我们需要创建 1 个重载 函数用于(>>) 提取 和1 个重载 函数用于(<<) insertion 这将适用于所有三个类.
我知道如何为一个类重载运算符,但对于多个类我不知道。
处理这个问题的一种方法是使用模板,然后使用 constexpr if 来处理不同类型的特定代码。这可能看起来像
// SFINAE to only enable is ABC is an A, B or C
template <typename ABC, std::enable_if_t<std::is_same_v<ABC, A> ||
std::is_same_v<ABC, B> ||
std::is_same_v<ABC, C>, bool> = true>
std:ostream operator <<(std::ostream& os, const ABC& abc)
{
if constexpr(std::is_same_v<ABC, A>)
return os << abc.a << " " << abc.b;
if constexpr(std::is_same_v<ABC, B>)
return os << abc.c << " " << abc.d << " " << abc.e;
if constexpr(std::is_same_v<ABC, C>)
return os << abc.f << " " << abc.g;
}
这有点作弊。它只是一个重载,但最多可以从中实例化 3 个不同的函数。