【问题标题】:Template Pointer as member模板指针作为成员
【发布时间】:2018-10-09 10:11:28
【问题描述】:

我有两个类“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> &"

提前谢谢

【问题讨论】:

  • template&lt;int Dim&gt; 是什么意思?
  • @CinCout 它是一个非类型模板参数
  • 那么它不应该是DTreeEmbedder&lt;int&gt;,而应该是修饰符类中的DTreeEmbedder&lt;42&gt;
  • @Konrad Rudolph DTreeEmbedder 是一个仅头文件,我需要命名空间才能访问另一个类

标签: c++ templates pointers forward-declaration


【解决方案1】:

template&lt;int Dim&gt; 更改为template&lt;class Dim&gt;

仔细查看错误,它说:-

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

在这里,您已在声明为template&lt;int Dim&gt;.的参数中分配了一个类

这里的"non-type" 代表的是您在模板中分配一个类,其参数是intNOT class)。

示例:

template<int Dim>
int Sum(int with)
{
    return Dim + with;
}


解释:

这里,“函数模板”是用int 类型的模板参数Dim 声明的。这是 variable 将保存 integer(不是一个类,a.k.a,你要在那里做的事情......),在使用时将分配给它。像这样:-

auto S = Sum&lt;2&gt;(2);

这里你在参数中分配了一个整数2,模板取Dim的值(本例中为2)并添加它在函数内部带有with,(在这种情况下为2)参数并返回表达式的结果。 (2 + 2 = 4)


你的问题出在这个构造函数中,

modifier(DTreeEmbedder&lt;int&gt;* e)

这里有一个问题,假设你已经将Dim声明为一个整数,现在在参数中添加一个类int是错误的......

应该是这样的:-

modifier(DTreeEmbedder&lt;111&gt;* e) // Or any other number, since Dim is an integer

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

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

DTreeEmbedder&lt;int&gt; /*Assigning a class to an integer (Dim in this case)*/

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

例如,DTreeEmbedder&lt;90&gt; 不等于 DTreeEmbedder&lt;91&gt; 或类似的东西...

亲切的问候,

鲁克斯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    相关资源
    最近更新 更多