我正试图在OpenSplice中构建一个C++程序,允许用户指定应该加载的类型。由于使用OpenSplice的IDL预处理器(IDLPP(生成的C++文件没有共享公共接口或基类,而是选择生成所有/大部分代码(我认为这是为了减少不必要的依赖关系(,这一点稍微复杂了一些。
我为这个问题创建的解决方案是首先用python脚本生成一个头文件,然后主程序可以调用它。这将允许生成所有的include语句,并根据定义添加IDLPP创建的类型。这个问题是以后引用那些定义。我想通过将定义的对象存储在容器中,然后简单地按数字引用它们来解决这个问题。
这里的问题是,由于它们不共享一个公共基类,C++不能提供一种简单的方法将它们存储在同一个容器中。作为参考,OpenSplice对象通常是这样创建的(半类似于STL中的元组或向量(:
dds::topic::Topic<moduleName::classType> variableName(params);
我想将这些不同的对象类型存储在一个容器中。重复和"丑陋"的代码在这里不是什么大问题,因为我无论如何都在生成这些文件。这是我目前尝试的实现:
#include <tuple>
template<class T, class U>
class TopicHolder{
public:
std::tuple<dds::topic::Topic<T>, dds::topic::Topic<U>> tuple_;
//empty constructor (error: no matching function for call to 'std::tuple<dds::topic::Topic<chat::NameServiceType, dds::topic::detail::Topic>,
// dds::topic::Topic<chat::ChatMessageType, dds::topic::detail::Topic>>::tuple()')
TopicHolder(){}
//or leave out the default constructor altogether (error: use of deleted function + note: implicity deleted because the default definition would be ill formed)
//also previous error
//put the template in the constructor? (see main below for issues)
TopicHolder(T, U){
dds::domain::DomainParticipant dp(0);
dds::topic::Topic<T> top1(dp, "top1");
dds::topic::Topic<U> top2(dp, "top2");
tuple_ = std::make_tuple(top1, top2);
}
void storeTopics(std::tuple<dds::topic::Topic<T>, dds::topic::Topic<U>> topics){
tuple_ = topics;
}
};
int main(){
//call templated constructor?
TopicHolder<chat::NameServiceType, chat::ChatMessageType> topicHolder();
//all good, now try to pull tuple out...
auto outTopic = std::get<0>(topicHolder.tuple_);
//error: request for member 'tuple_' in 'topicHolder', which is of non-class type 'TopicHolder<chat::NameServiceType, chat::ChatMessageType>()'
//leave out brackets in TopicHolder constructor: error: no matching function for call to 'TopicHolder<chat::NameServiceType, chat::ChatMessageType>::Topic()'
return 0
}
正如你从评论中看到的,这会根据我试图修改的部分产生各种不同的错误。似乎最接近的方法是使用TopicHolder(T, U)
构造函数,但当我尝试实际读取元组时,这种方法失败了
存在令人烦恼的解析问题
// Function declaration
TopicHolder<chat::NameServiceType, chat::ChatMessageType> topicHolder();
使用TopicHolder<chat::NameServiceType, chat::ChatMessageType> topicHolder;
或TopicHolder<chat::NameServiceType, chat::ChatMessageType> topicHolder{};
然后,您的成员似乎不是默认可构造的,所以您必须使用初始值设定项列表(这无论如何都很好(。
你可以这么做:
template<class T, class U>
class TopicHolder{
public:
dds::domain::DomainParticipant dp_{0};
std::tuple<dds::topic::Topic<T>, dds::topic::Topic<U>> tuple_;
TopicHolder() : tuple_{dds::topic::Topic<T>(dp, "top1"), dds::topic::Topic<U>(dp, "top2")} {
}
void storeTopics(std::tuple<dds::topic::Topic<T>, dds::topic::Topic<U>> topics){
tuple_ = topics;
}
};
int main(){
TopicHolder<chat::NameServiceType, chat::ChatMessageType> topicHolder;
auto& outTopic = std::get<0>(topicHolder.tuple_);
// ...
}