gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:54:51 25 4
gpt4 key购买 nike

我有课

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com