本文介绍了异常重复的模板模式非法调用非静态成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在尝试大量模板元编程,尤其是使用CRTP时,遇到了标题错误.特别是错误C2352'MeshComponent :: InternalSetEntity':非法调用了非静态成员函数.

I've been attempting a lot of template meta programming lately, particularly using CRTP, and have come across the titular error. Specifically error C2352 'MeshComponent::InternalSetEntity': illegal call of non-static member function.

我的代码的一个最小,完整和可验证的摘要如下:

A Minimal, Complete, and Verifiable snippit of my code is as such:

Component.h

Component.h

class Entity //Forward declaration

template<class T, EventType... events>
class Component {
private:
    short entityID;
public:
    void SetEntity(Entity& _entity) { entityID = _entity.GetId(); T::InternalSetEntity(_entity); }
protected:
    void InternalSetEntity(Entity& _entity) {}
};

MeshComponent.h

MeshComponent.h

#include "Component.h"
class MeshComponent : public Component<MeshComponent> {
    friend class Component<MeshComponent>;
protected:
    void InternalSetEntity(Entity& _entity);
};

MeshComponent.cpp

MeshComponent.cpp

#include "MeshComponent.h"
void MeshComponent::InternalSetEntity(Entity& _entity) {
    //Nothing yet
}

Entity.h

class Entity {
private:
    short id;
public:
    short GetId() {return id;}
};

我没有声明任何静态函数,也不想声明.实际上,我要求它们成为成员函数,因为它们将对实例特定的数据进行操作.

I am not declaring any static functions, nor do I want to. In fact I require these to be member functions as they will operate on instance specific data.

如果有人知道为什么会发生此错误,以及可能的解决方案,我将不胜感激.预先感谢.

If someone knows why this error is occurring and a possible solution to the problem I would greatly appreciate it. Thanks in advance.

推荐答案

您知道并确保 MeshComponent 继承自 Component< MeshComponent> ,但编译器不会知道:就 Component 的定义而言, Component< T> T 是不相关的.您需要明确执行向下转换:

You know and ensure that MeshComponent inherits from Component<MeshComponent>, but the compiler doesn't know that: as far as it knows in the definition of Component, Component<T> and T are unrelated. You need to perform the downcast explicitly:

static_cast<T*>(this)->InternalSetEntity(_entity);

这篇关于异常重复的模板模式非法调用非静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 16:33