根据模板参数的不同,以不同的方式重载运算符



我有一个类

template<int n> MyClass<n>

我试图为其定义CCD_ 1。我希望能够执行MyClass&MyClass,还有MyClass&MyClass<1>(或者MyClass<1>&MyClass也适用于我(显然具有不同的功能。

template <size_t n>
struct MyClass
{
//...a lot of stuff
MyClass<n> operator&(const MyClass<n> &other) const;
MyClass<n> operator&(const MyClass<1> &other) const;
}

然而,我无法编译它,因为在n为1的情况下,它们会发生冲突。我试着添加SFINAE,但显然我对它的理解不够好,无法在这种情况下使用它。

template <size_t n>
struct MyClass
{
//...a lot of stuff
MyClass<n> operator&(const MyClass<n> &other) const;
std::enable_if_t<n != 1, MyClass<n>> operator&(const MyClass<1> &other) const;
}

不适用于确保n为1的情况不会引起问题。我认为这是因为SFINAE适用于函数模板参数本身,而不适用于类模板参数。

我相信我可以对MyClass<1>进行专门化,但之后我必须复制MyClass<n>的所有内容。有什么简单的解决办法吗?

SFINAE仅适用于模板。您可以将第一个operator&模板制作为:

template <size_t n>
struct MyClass
{
//...a lot of stuff
template <size_t x>
std::enable_if_t<x == n, MyClass<x>> // ensure only MyClass<n> could be used as right operand 
operator&(const MyClass<x> &other) const;
// overloading with the template operator&
// non-template is perferred when MyClass<1> passed
MyClass<n> operator&(const MyClass<1> &other) const;
};

实时

您可以使用约束(需要c++20(

template <size_t n>
struct MyClass
{
MyClass<n> operator&(const MyClass<n> &) const { std::cout << "1n"; return {}; }
MyClass<n> operator&(const MyClass<1> &) const requires (n!=1) { std::cout << "2n"; return {}; }
};

小心运算符重载,不要赋予运算符超出预期的含义。在几乎所有情况下,最好创建具有可读名称的函数(为了可维护性(。

你想做什么,我认为可以用";如果constexpr";,示例:

#include <utility>
#include <iostream>
template <std::size_t N>
struct MyClass
{
void do_something() const
{
if constexpr (N == 1)
{
std::cout << "behavior 1n";
}
else
if constexpr (N == 2)
{
std::cout << "behavior 2n";
}
}
};
int main()
{
MyClass<1> c1;
MyClass<2> c2;
c1.do_something();
c2.do_something();
return 0;
}

最新更新