我有一个奇怪的行为,一个模板方法调用一个模板变量方法,我找不到什么问题。我正在使用VisualStudioCommunity2017。
编译错误出现在以下方法中:
// 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'
// ...
}如果我试图在此方法中使用默认构造函数,则会出现上述编译错误。在派生类中调用此方法,此处:
// MyScene.cpp
#include "AScene.hpp"
void MyScene::initialize(void) {
AScene::initialize_<Level>();
// If I call root->addComponent<Scriptable>() directly here, its working perfectly
}下面是addComponent模板变量方法的实现:
// AGameObject.hpp
template <typename C, typename ...Args>
void AGameObject::addComponent(Args&& ... args) {
entity_.assign<C>(std::forward<Args>(args) ...);
}因为它是库的一部分,所以我不能向您展示assign()代码,但是当我不在_initialize__中调用它时,这段代码总是可以工作的。
这是我的脚本类:
// Scriptable.hpp
struct Scriptable {
Scriptable(void) = default;
Scriptable(int i) {} // remember, used to bypass the default constructor
// ...
};实际上,当我在模板方法addComponent中调用_initialize__方法时,编译器似乎忽略/找不到默认的构造函数。你知道我做错了什么吗?
如果您需要进一步的信息,请告诉我。
编辑:
我刚刚检查了库中的assign()实现,构造函数的调用如下所示:
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)'
发布于 2020-04-16 15:35:28
我惊讶地发现这个问题没有答案。我也遇到过同样的问题,我发现这样做是可行的:
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 tooPS,这是我很久以前就学过的怪癖之一,但实际上还不知道为什么需要它。这里解释了它背后的理论:Calling template function within template class,但是我还是不明白为什么带参数的调用编译得很好。如果有人能详细说明的话,我会很感激的。
https://stackoverflow.com/questions/55076308
复制相似问题