c++ - 推导使用循环模板的函数的参数

标签 c++ templates

我从下面的代码中得到了错误。怎么了?一切似乎就绪。

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 基类的函数。这将尝试切片对象,复制基本子对象并丢弃使其成为 LauncherCommandLauncherCommandChangeSimulation 的所有内容。即使那样行得通,也不是您想要的;在这种情况下,它不起作用,因为基类是抽象的,因此不能实例化为一个完整的对象。

为了在菜单中存储多态对象,您需要某种间接方式。看起来您需要进一步的非模板基类,AddLeaf 将需要获取并存储一个(最好是智能的)指向它的指针。

关于c++ - 推导使用循环模板的函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400339/

相关文章:

c++ - C++ 模板中的 const 引用

c++ - 为什么std::forward_list::: remove和std::erase <std::forward_list>具有不同的值类型?

c++ - 这个模板定义有什么问题?

c++ - 以 X-Y 坐标给出的点之间的最短路径距离

c++ - 在eclipse中包含来自其他文件夹的文件

c++ - 处理嵌套 std::any_of 的模板函数

c++ - 如何在不保存文件的情况下制作打印屏幕并将其发送到 FTP 服务器?我的工作代码将文件保存到 HDD

c++ - boost::lexical_cast 如何只采用一种模板类型?

powershell - 如何使用 PowerShell 导入文件,并将所有现有的占位符变量替换为脚本中定义的变量?

c++ - 在 x86 程序集中更改数组的值(嵌入在 C++ 中)