基于另一个成员参数将函数调用从类传递给它的一个成员

Pass function call from a class to one of its members based on another member parameter

本文关键字:成员 一个 参数 另一个 函数调用      更新时间:2023-10-16

假设我有以下class A,它通过不同的函数调用和包装器传递。

class A{
std::vector<int> a;
public:
int getSize const {return a.size();}
int getVal(int i) const {return a[i];}
// other private and public members and functions 
}

现在出于某种原因,我需要相同的类,但有一个双向量。我无法将此类模板化,因为有许多函数签名我无法更改。建议将A重命名为A0,将其模板化,创建包含A0<int>A0<double>的新A,如下所示:

template <typename T>
class A0{
std::vector<T> a;
public:
int getSize const {return a.size();}
T getVal(int i) const {return a[i];}
// other private and public members and functions 
}
class A{
// only one of the following will be initialized in the constructor and the other one will be null.
std::shared_ptr<A0<int>> iA;
std::shared_ptr<A0<double>> dA;
// also the following flag will be set in the constructor
bool isInt;
}

这就是问题:如果我想在以前访问、更改或刚刚传递类A实例的代码的不同位置进行最小的更改,该怎么办?例如,在旧代码的另一部分中考虑这一点:

A x;
int n = x.getSize();

有没有一种方法可以保留旧代码,而不在新的A类中实现方法getSize(),该类将包含if条件语句并基于isInt返回iA->getSize()dA->getSize()?有聪明的方法吗?

对于在使用(主要是传递(旧A的代码的不同部分中实现最小修改的目标,还有其他建议吗?

}

如果这只是传递对象(或对它的引用(,而不是实际使用对象的任何成员,那么您可以简单地使用std::variant:

using A = std::variant<A0<int>, A0<double>>;

在实际使用成员的点上,使用std::visit来确定类型并对其执行操作


如果传递仅通过引用发生,则使A成为A0<T>的空基类也将起作用。然后,您可以使用static_cast<A0<int>&>(...)static_cast<A0<double>&>(...)强制转换回真实类型,以使用目的地的成员。但是,必须确保强制转换为传递对象的实际类型,否则将有未定义的行为。

另一种选择是dynamic_cast而不是static_cast,如果类型不匹配,它将抛出或返回一个空指针。但这需要基类A有一个虚拟方法来实现多态性。

std::variant可能就是您所需要的。创建一个buffer类并将所有容器操作转发给它。在A类中不需要更改太多,但应该在buffer中模仿std::vector<T>,我实现了size()const subscript operator。以下是基本演示。

#include <variant>
#include <vector>
#include <iostream>
struct store_as_int {};
struct store_as_double {};
class buffer {
public:
buffer( store_as_int ) : data { std::vector<int>{} } {
std::cout << "I am storing numbers as int" << std::endl;
}
buffer( store_as_double ) : data { std::vector<double>{} } {
std::cout << "I am storing numbers as double" << std::endl;
}
[[nodiscard]] std::size_t size() const noexcept {
std::size_t s;
std::visit( [ &s ]( auto&& arg ) {
s = arg.size(); 
} , data );
return s;
}
[[nodiscard]] double operator[]( std::size_t idx ) const {
double s;
std::visit( [ &s , idx ]( auto&& arg ) {
s = arg[ idx ]; 
} , data );
return s;
}
private:
std::variant< std::vector<int> , std::vector<double> > data;
};
class A{
buffer a;
public:
A() : a { store_as_int{} } {}
A( store_as_double ) : a { store_as_double {} } {   }
int getSize() const { return a.size(); }
int getVal(int i) const { return a[i]; }
};
int main()
{
A x;
A y { store_as_double{} };
int n = x.getSize();
int t = x.getSize();
std::cout << n << std::endl;
std::cout << t << std::endl;
}

输出:

我将数字存储为int
我将数据存储为double
0
0

运行在线

相关文章: