模板指针作为成员

时间:2018-10-09 10:11:29

标签: c++ templates pointers forward-declaration

我有两个类“ DTreeEmbedder”和“修饰符”。 Embedder是一个模板类,我想操纵“ DTreeEmbedder”的成员变量。

DTreeEmbedder类:

class modifier; //forward declaration of modifier

using namespace ogdf;
using namespace ogdf::energybased::dtree;

template<int Dim>
class DTreeEmbedder
{
  public:
  //! constructor with a given graph, allocates memory and does 
  initialization
  explicit DTreeEmbedder(GLFWwindow * w, const Graph& graph);

  //! destructor
  virtual ~DTreeEmbedder();

  modifier* m_modifier;

在构造函数中

  template<int Dim>
  DTreeEmbedder<Dim>::DTreeEmbedder(GLFWwindow * w, const Graph& graph) : 
             m_graph(graph)
  {
        m_modifier = new modifier();
  }

两个对象都需要彼此访问,因此需要向前声明。

#pragma once

#include "DTreeEmbedder.h"

class modifier
{
  public:
    modifier(DTreeEmbedder<int>* e);
    ~modifier();

    DTreeEmbedder<int>* m_embedder;

    void pca_project(int pc1,int pc2);
 };

pca_project是一个应该在m_embedder中更改值/调用函数的函数

在修饰符的构造函数中:

modifier::modifier(DTreeEmbedder<int>* e)
{
   m_embedder = e;
}

pca功能:

void modifier::pca_project(int pc1, int pc2)
{
   m_embedder->stop();
}

因此,我的方法是:

  1. 创建DTreeEmbedder
  2. DTreeEmbedder使用自身的指针创建修饰符
  3. 修饰符获得了指向DTreeEmbedder的指针,现在可以更改该对象的值

我的错误是:

"int": Invalid type for the non-type template parameter "Dim"
This pointer can not be converted from "DTreeEmbedder" to "DTreeEmbedder <Dim> &"

提前谢谢

1 个答案:

答案 0 :(得分:1)

  

template<int Dim>更改为template<class Dim>

OR

仔细查看错误,它说:-

"int": Invalid type for the non-type template parameter "Dim"

在这里,您已经在声明为template<int Dim>.

的参数中分配了一个类。

这里的“非类型” 的意思是,您正在模板中分配一个类,该类的参数为int {{1 }}。

  

示例:

class
     


  说明:

     

此处,使用类型为template<int Dim> int Sum(int with) { return Dim + with; } 的模板参数Dim声明了“功能模板”。这是变量,将保存整数(不是类,也就是您要在其中执行的操作...),该变量将在使用时分配给它。像这样:-

     

int

     

在这里,您在参数中分配了整数auto S = Sum<2>(2);,模板采用的值是2(在这种情况下,为 2 ),并将其与函数内的Dim(在这种情况下为 2 )参数相加,并返回表达式的结果。 ( 2 + 2 = 4 )   


  问题出在哪里呢?

     

with

     

在这里,存在一个问题,因为您已经将modifier(DTreeEmbedder<int>* e)声明为整数,现在在参数内添加类Dim是错误的...

     

所以应该是:-

     

int

     

将此模板参数视为一个真正的整数变量,因此您正在执行以下操作:-

     

modifier(DTreeEmbedder<111>* e) // Or any other number, since Dim is an integer

     

     

int Dim = int; /*Which is a type (class)*/

     

另一个错误是赋值错误,请检查两个变量是否相同,因为Dim是整数,因此即使模板内部分配的整数值也必须匹配。

     

就像DTreeEmbedder<int> /*Assigning a class to an integer (Dim in this case)*/不等于DTreeEmbedder<90>或类似的东西...

亲切的问候,

Ruks。