首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用默认构造函数时模板变量编译错误

调用默认构造函数时模板变量编译错误
EN

Stack Overflow用户
提问于 2019-03-09 10:21:10
回答 1查看 163关注 0票数 1

我有一个奇怪的行为,一个模板方法调用一个模板变量方法,我找不到什么问题。我正在使用VisualStudioCommunity2017。

编译错误出现在以下方法中:

代码语言:javascript
复制
// AScene.hpp
#include "Scriptable.hpp"

template <typename T>
void AScene::initialize_(void) {
    std::shared_ptr<AGameObject> root = std::make_shared<T>();

    // ...
    root->addComponent<Scriptable>(3); // it works (3 is just a random value to bypass the default constructor, see below the Scriptable struct definition)
    root->addComponent<Scriptable>(); // error C2760 unexpected token ')', expected 'expression'
    // ...
}

如果我试图在此方法中使用默认构造函数,则会出现上述编译错误。在派生类中调用此方法,此处:

代码语言:javascript
复制
// MyScene.cpp
#include "AScene.hpp"

void MyScene::initialize(void) {
    AScene::initialize_<Level>();
    // If I call root->addComponent<Scriptable>() directly here, its working perfectly
}

下面是addComponent模板变量方法的实现:

代码语言:javascript
复制
// AGameObject.hpp
template <typename C, typename ...Args>
void AGameObject::addComponent(Args&& ... args) {
    entity_.assign<C>(std::forward<Args>(args) ...);
}

因为它是库的一部分,所以我不能向您展示assign()代码,但是当我不在_initialize__中调用它时,这段代码总是可以工作的。

这是我的脚本类:

代码语言:javascript
复制
// Scriptable.hpp
struct Scriptable {
    Scriptable(void) = default;
    Scriptable(int i) {} // remember, used to bypass the default constructor
    // ...
};

实际上,当我在模板方法addComponent中调用_initialize__方法时,编译器似乎忽略/找不到默认的构造函数。你知道我做错了什么吗?

如果您需要进一步的信息,请告诉我。

编辑:

我刚刚检查了库中的assign()实现,构造函数的调用如下所示:

代码语言:javascript
复制
C(std::forward<Args>(args) ...);

如果您想要检查它,下面是链接:https://github.com/alecthomas/entityx/blob/master/entityx/Entity.h#L648

这正是编译器告诉我的:

1>AGameObject.cpp 1>path\ascene.hpp(89): error C2760: syntax error: unexpected token ')', expected 'expression' 1>path\ascene.hpp(89): note: This diagnostic occurred in the compiler generated function 'void AScene::initialize_(void)'

EN

回答 1

Stack Overflow用户

发布于 2020-04-16 15:35:28

我惊讶地发现这个问题没有答案。我也遇到过同样的问题,我发现这样做是可行的:

代码语言:javascript
复制
    root->addComponent<Scriptable>(3); // it works (3 is just a random value to bypass the default constructor, see below the Scriptable struct definition)
    root->addComponent<Scriptable>(); // error C2760 unexpected token ')', expected 'expression'
    root->template addComponent<Scriptable>(); //it works too

PS,这是我很久以前就学过的怪癖之一,但实际上还不知道为什么需要它。这里解释了它背后的理论:Calling template function within template class,但是我还是不明白为什么带参数的调用编译得很好。如果有人能详细说明的话,我会很感激的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55076308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档