【问题标题】:Inherit from template class problems从模板类问题继承
【发布时间】: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


【解决方案1】:
  1. data 声明为指针。
  2. 提供getter 和setter 函数。在这些函数中,请确保从堆中分配数据。

这是更新后的课程。

template<typename T>
struct APP_Interface{
    APP_Interface* shared;
    Mutex m; 
    T* data;

    APP_Interface : data(nullptr) {}

    T const& getData() const
    {
       if (!data)
       {
          data = new T;
       }
       return *data;
    }

    void setData(T const& newData)
    {
       if (!data)
       {
          data = new T;
       }
       *data = newData;
    }

    virtual void publish(){
    //copy data from this->data to shared->data
    }

    virtual void receive(){
    //copy data from shared->data to this->data 
    }
};

【讨论】:

  • 我试图避免动态内存分配:)
  • 在这种情况下,您必须为您的课程找到不同的设计。您不能使用 CRTP 模式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多