如何将 std::vector 个函数指针初始化为运算符重载?
How to initialize std::vector of function pointers to operator overloads?
我试图用指向四个运算符重载成员函数的指针创建一个 std::vector
。这有什么问题:
struct Fractal
{ int dividee;
int divisor;
Fractal operator +(Fractal other)
{ [not important]
}
Fractal operator -(Fractal other)
{ [not important]
}
Fractal operator *(Fractal other)
{ [not important]
}
Fractal operator /(Fractal other)
{ [not important]
}
};
int main()
{ Fractal fractal = Fractal{3, 10};
typedef Fractal(*fractalOperator)(Fractal, Fractal);
std::vector<fractalOperator> ops =
{ &Fractal::operator +,
&Fractal::operator -,
&Fractal::operator *,
&Fractal::operator /
};
}
编译器说
error: could not convert '{&Fractal::operator+, &Fractal::operator-, &Fractal::operator*, &Fractal::operator/}' from '<brace-enclosed initializer list>' to 'std::vector<Fractal (*)(Fractal, Fractal)>'
};
这不是很有帮助。什么是正确的方法?我正在使用 c++14.
你的 typedef
是指向函数的指针,它需要两个 Fractal
和 returns 一个 Fractal
。您想要的是 pointer to member function,它具有不同的语法。
typedef Fractal(Fractal::*fractalOperator)(Fractal);
或者,使用 using
别名,我觉得这样更容易阅读
using fractalOperator = Fractal(Fractal::*)(Fractal);
一种方法是:
std::vector<std::function<Fractal(Fractal, Fractal)>> ops = {
[](Fractal l, Fractal r){ return l + r; },
[](Fractal l, Fractal r){ return l - r; },
[](Fractal l, Fractal r){ return l * r; },
[](Fractal l, Fractal r){ return l / r; },
};
这样做的好处是,无论运算符是作为成员函数还是自由函数实现都无关紧要。
在幕后,lambda 存储在具有正确调用签名的 function
对象中,那些存储在 vector
.
中
我试图用指向四个运算符重载成员函数的指针创建一个 std::vector
。这有什么问题:
struct Fractal
{ int dividee;
int divisor;
Fractal operator +(Fractal other)
{ [not important]
}
Fractal operator -(Fractal other)
{ [not important]
}
Fractal operator *(Fractal other)
{ [not important]
}
Fractal operator /(Fractal other)
{ [not important]
}
};
int main()
{ Fractal fractal = Fractal{3, 10};
typedef Fractal(*fractalOperator)(Fractal, Fractal);
std::vector<fractalOperator> ops =
{ &Fractal::operator +,
&Fractal::operator -,
&Fractal::operator *,
&Fractal::operator /
};
}
编译器说
error: could not convert '{&Fractal::operator+, &Fractal::operator-, &Fractal::operator*, &Fractal::operator/}' from '<brace-enclosed initializer list>' to 'std::vector<Fractal (*)(Fractal, Fractal)>'
};
这不是很有帮助。什么是正确的方法?我正在使用 c++14.
你的 typedef
是指向函数的指针,它需要两个 Fractal
和 returns 一个 Fractal
。您想要的是 pointer to member function,它具有不同的语法。
typedef Fractal(Fractal::*fractalOperator)(Fractal);
或者,使用 using
别名,我觉得这样更容易阅读
using fractalOperator = Fractal(Fractal::*)(Fractal);
一种方法是:
std::vector<std::function<Fractal(Fractal, Fractal)>> ops = {
[](Fractal l, Fractal r){ return l + r; },
[](Fractal l, Fractal r){ return l - r; },
[](Fractal l, Fractal r){ return l * r; },
[](Fractal l, Fractal r){ return l / r; },
};
这样做的好处是,无论运算符是作为成员函数还是自由函数实现都无关紧要。
在幕后,lambda 存储在具有正确调用签名的 function
对象中,那些存储在 vector
.