是否可以將一些具有相同邏輯但不同運算子的類運算子合并為不復制粘貼。例如,我有帶操作員的課程 =,-=:
class Matrix {
public:
Functor& operator =(const Functor& rhs) {
for (int i = 0; i < num; i) {
v[i][j] = rhs.v[i][j];
}
return *this;
}
Functor& operator-=(const Functor& rhs) {
for (int i = 0; i < num; i) {
v[i][j] -= rhs.v[i][j];
}
return *this;
}
private:
int rows_ {};
int columns_ {};
std::vector<std::vector<double>> matrix_;
};
C 是否有類似的東西:
Functor& operator( =, -=)(const Functor& rhs) {
for (int i = 0; i < num; i) {
v[i][j] ( =, -=) rhs.v[i][j];
}
return *this;
}
uj5u.com熱心網友回復:
您可以通過將 lambda 傳遞給通用實作來做到這一點:
class Matrix {
private:
template<typename Op>
Functor& opImpl(const Functor& rhs, Op op) {
for (int i = 0; i < rows_; i) {
for (int j = 0; j < columns_; j) {
Op(v[i][j], rhs.v[i][j]);
}
}
return *this;
}
public:
Functor& operator =(const Functor& rhs) {
return opImpl(rhs, [&](double& l, const double r) { r = l; });
}
Functor& operator-=(const Functor& rhs) {
return opImpl(rhs, [&](double& l, const double r) { r -= l; });
}
private:
int rows_ {};
int columns_ {};
std::vector<std::vector<double>> matrix_;
};
通常,您首先要實施operator andoperator-并實施operator =andoperator-=就前者而言。在這種情況下,如果您使用的是 c 14 或更高版本(謝謝@StoryTeller) ,則可以使用std::plus<double>()and來表示 lambda。std::minus<double>()
您可以通過將運算子放在基類中、將其用作命名空間或僅通過宏來進一步節省空間:
#define IMPLEMENT_OP(RET, OP, ARG, T) \
RET operator ## OP ## (ARG rhs) { \
return opImpl(rhs, T::operator ## op); \
}
解決這個問題的另一種方法 - 仍然通過委托 - 是使用 constexpr if:
class Matrix {
private:
template<char op1, char op2 = ' '>
Functor& opImpl(const Functor& rhs) {
for (int i = 0; i < rows_; i) {
for (int j = 0; j < columns_; j) {
if constexpr (op1 == ' ' && op2 == '=') {
v[i][j] = rhs.v[i][j];
}
if constexpr (op1 == '-' && op2 == '-') {
v[i][j] -= rhs.v[i][j];
}
// TODO: further ops, error handling here
}
}
return *this;
}
public:
Functor& operator =(const Functor& rhs) {
return opImpl<' ', '='>(rhs);
}
Functor& operator-=(const Functor& rhs) {
return opImpl<'-', '='>(rhs);
}
private:
int rows_ {};
int columns_ {};
std::vector<std::vector<double>> matrix_;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498103.html
上一篇:如何回傳類實體的默認屬性?
