我有一堂課
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>. 有什么簡單的解決方案嗎?
uj5u.com熱心網友回復:
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;
};
居住
uj5u.com熱心網友回復:
您可以使用約束(需要 c 20)
template <size_t n>
struct MyClass
{
MyClass<n> operator&(const MyClass<n> &) const { std::cout << "1\n"; return {}; }
MyClass<n> operator&(const MyClass<1> &) const requires (n!=1) { std::cout << "2\n"; return {}; }
};
uj5u.com熱心網友回復:
小心運算子多載,不要給運算子賦予超出預期的意義。在幾乎所有情況下,最好創建具有??可讀名稱的函式(為了可維護性)。
你想做什么我認為可以用“if constexpr”來完成,例如:
#include <utility>
#include <iostream>
template <std::size_t N>
struct MyClass
{
void do_something() const
{
if constexpr (N == 1)
{
std::cout << "behavior 1\n";
}
else
if constexpr (N == 2)
{
std::cout << "behavior 2\n";
}
}
};
int main()
{
MyClass<1> c1;
MyClass<2> c2;
c1.do_something();
c2.do_something();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397257.html
