c++ - 如何使类的构造函数根据参数访问重载函数?
问题描述
我有以下场景:该类internalEntity
应该以许多不同的形式(例如,等)存储boolCloud
数据std::vector<TRIANGLE>
。创建此对象时,构造函数应该initEntity()
根据参数调用正确的函数。如何在不重载构造函数和函数的情况下做到这一点?
例如执行时
internalEntity myEntity(bCloud, "My bool Cloud");
其中bCloud是boolCloud
我想要initEntity()
调用的第一个函数。
此示例不起作用,但该typename T
部分应该说明我想要做什么。
class internalEntity
{
public:
internalEntity(typename T, std::string name) { initEntity(T, name); };
void initEntity(boolCloud& bCloud, std::string name);
void initEntity(std::vector<TRIANGLE>& triMesh, std::string name);
void initEntity(std::vector<dvec>& pointCloud , std::string name);
void deleteEntity();
//...
};
解决方案
这种情况的一个常见解决方案是使用助手类的帮助:
template<typename T> struct initialize_me;
class internalEntity
{
public:
internalEntity(typename T, std::string name)
{
initialize_me<T>::please(*this, name };
// ... The rest of the class declaration.
这个前向声明允许您在处理手头的业务之前定义类的其余部分。到那时,这变成了一个简单的专业化案例:
template<> struct initialize_me<bool> {
inline static void please(internalEntity *me, const std::string &name)
{
boolCloud whatever_this_is;
me->initEntity(whatever_this_is, name);
}
};
对于所有其他必要的专业也是如此。从您的问题中不清楚重载initEntity
s 的第一个参数来自哪里。如果它们是同一类的成员me
,通常可以通过指针将它们传递到此处。如有必要,为了加强访问,助手类可以是一个friend
.
如果必须在构造函数的初始化部分进行初始化,并且不能像在这种情况下那样推迟到主体,那就有点冒险了。然后,解决方案将取决于确切的细节,并且在找出解决方案之前将需要一个具体的具体示例。
推荐阅读
- amazon-web-services - 如何在 AWS CLI 中选择配置文件?
- android - ConstraintLayout 以编程方式将约束更改为可移动视图
- workfusion - 执行 OCR 时出错
- nginx - Lua nginx从POST头中提取目标路径
- excel - 使用 VBA 单击下拉列表中的元素
- postgresql - 舍入值 Postgresql
- java - 如何在片段中使用 EventBus?
- git - 使用 git 删除已删除的文件夹
- wso2esb - WSO2 esb 在什么情况下端点可以处于关闭状态
- php - TCPDF:getimagesize():SSL 操作失败,代码 1 错误:1416F086:SSL 例程:tls_process_server_certificate:证书验证失败