我对调用模板可变参数方法的模板方法有一种奇怪的行为,但我找不到问题所在。我正在使用Visual Studio Community 2017。
在以下方法中出现编译错误:
// 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 _中调用它时,该代码将始终有效。
这是我的可编写脚本的类:
中调用addComponent方法时,似乎编译器只是忽略/找不到默认构造函数。你知道我在做什么错吗?// Scriptable.hpp struct Scriptable { Scriptable(void) = default; Scriptable(int i) {} // remember, used to bypass the default constructor // ... };
实际上,当我在模板方法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)'
我对调用模板可变参数方法的模板方法有一种奇怪的行为,但我找不到问题所在。我正在使用Visual Studio Community2017。出现编译错误...
我很惊讶地看到这个问题没有答案。我遇到了同样的问题,发现这可行: