c++ - 根据模板参数以不同方式重载运算符

标签 c++ templates

我有课

template<int n> MyClass<n>

我试图为其定义 operator & .我希望能够执行 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;
};

LIVE

关于c++ - 根据模板参数以不同方式重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70507626/

相关文章:

使用 shared_ptr 函数模板的 C++ 实例化

C++ 中的模板初始化

c++ - 我如何声明我的类的实例?

c++ - 在 Windows 上使用 openssl 库生成随 secret 钥/数据

C++继承模板类

c++ - 为什么函数重载有歧义,而模板重载却没有歧义?

css - 为其他站点高效地重用(设计不佳的)JSON 模板?

c++ - 在函数中返回大对象

c++ - Qt Creator 调试器中 vector 成员的值是多少?

c++ - 使用std::future监视和控制线程执行类成员函数(c++)?