【发布时间】:2014-09-05 18:23:23
【问题描述】:
大家好,我想做这样的事情:
template<typename T>
struct APP_Interface{
APP_Interface* shared;
Mutex m;
T data;
virtual void publish(){
//copy data from this->data to shared->data
}
virtual void receive(){
//copy data from shared->data to this->data
}
};
struct MyInterface : APP_Interface<MyInterface>{
float MyData1;
float MyData2;
};
我遇到了(我猜这并不奇怪):
error: 'APP_Interface<T>::data' has incomplete type
error: forward declaration of 'struct MyInterface '
有没有办法解决这个问题?
编辑:我想要实现的目标
我有两个线程。 Thread1 产生实时数据,Thread2 消费这些数据。现在我想让 Thread1 通过共享数据和互斥锁来与 Thread2 共享数据。
实际上有很多线程,很多不同的数据接口共享不同的数据。因此,我想要一种简单而优雅的方式来创建和使用界面。
我想创建一个类似这样的界面:
struct MyInterface : ??? {
float MyData1;
float MyData2;
};
那么当我应该使用它时,我只想:
//Thread1.hpp
class thread1{
void run(){
interface.MyData1 = 100;
interface.publish();
}
public:
MyInterface interface;
}
//And something similar for thread2 at the receiving end
最后,我想通过让 main.c 创建两者之间的链接并分配共享结构来实现一些“依赖注入”。例如:
//main.cpp
void main(){
//Bind interfaces:
MyInterface interface({ &thread1.interface, //PROVIDER
&thread2.interface, //CONSUMER
});
}
我不知道这个解释是否有意义:)
【问题讨论】:
-
这没有意义。你想达到什么目的?通常,您要么希望将派生类模板化,要么希望专门化 APP_Interface。我猜你想要这个:'struct MyData { float MyData1;浮动我的数据2; }; APP_Interface
myDataPublisher;' -
好吧,显然这会失败。你会有一个 MyInterface,它是一个 App_Interface,它包含一个 MyInterface,它是一个 App_Interface,它包含一个......我认为我们无法回答如何解决这个问题,除非你告诉我们你打算如何使用它。就我个人而言,我会发布和接收摘要并完成它。
-
T data;应该是T* data;无论如何请看here,如何正确创建和使用CRTP。 -
我试图避免动态内存^^。
-
@MadScienceDreams 检查更新。
标签: c++ templates inheritance