我从下面的代码中得到了错误。怎么了?一切似乎就绪。
error C2784: 'void Menu::AddLeaf(Command,const int)' : could not deduce template argument for 'Command' from 'LauncherCommandChangeSimulation'
Command.h
template <class Receiver>
class Command
{
virtual void Execute() = 0;
...
};
LauncherCommand.h
#include "Menu/Command.h"
#include "Internal/Launcher.h"
class LauncherCommand : public Command<Launcher>
{ ... };
class LauncherCommandChangeSimulation : public LauncherCommand
{ ... };
Menu.h
template <class T>
class Command;
class Menu
{
public:
template <class T>
void AddLeaf(Command<T> command, const int parentId);
};
游戏.cpp
#include "Internal/Launcher.h"
#include "Menu/Menu.h"
#include "Menu/LauncherCommand.h"
LauncherCommandChangeSimulation command(...);
menu.AddLeaf(command, ...); // Error here
如果我更改对 AddLeaf 的调用
menu.AddLeaf<Launcher>(command, simsNodeId);
然后我得到下一个错误
error C2770: invalid explicit template argument(s) for 'void Menu::AddLeaf(Command,const int)'
最佳答案
您正在尝试将派生类对象传递给按值采用 Command
基类的函数。这将尝试切片对象,复制基本子对象并丢弃使其成为 LauncherCommand
和 LauncherCommandChangeSimulation
的所有内容。即使那样行得通,也不是您想要的;在这种情况下,它不起作用,因为基类是抽象的,因此不能实例化为一个完整的对象。
为了在菜单中存储多态对象,您需要某种间接方式。看起来您需要进一步的非模板基类,AddLeaf
将需要获取并存储一个(最好是智能的)指向它的指针。
关于c++ - 推导使用循环模板的函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400339/