【问题标题】:C++ Template parameter deduction from array dimensions [duplicate]C++模板参数从数组维度推导[重复]
【发布时间】:2013-04-24 20:21:21
【问题描述】:

我需要你的帮助来参数化具有 int 值的模板。

看起来是这样的:

SpriteSwitcher.h:

template<int N >
    bool initWithFilesArray(std::string (&fileNames)[N],int width, const CCPoint position);

SpriteSwitcher.cpp:

    template<int N >
    bool SpriteSwitcher::initWithFilesArray(std::string (&fileNames)[N], int width, const CCPoint position)
    {
      return true;
    }

然后我尝试用我的 initWithFileArray 函数初始化 SpriteSwitcher 类

std::string g[2] = {"hello", "world"};
SpriteSwitcher *s = new SpriteSwitcher();
s->initWithFilesArray(g, visibleSize.width, origin);

我收到以下错误:

error lnk2019 无法解析的外部符号“”public: bool __thiscall SpriteSwitcher::initWithFilesArray(class std::basic_string,class std::allocator > (&)[2],int,class cocos2d::CCPoint)” (??$initWithFilesArray@$01@SpriteSwitcher@@QAE_NAAY01V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HVCCPoint@cocos2d@@@Z)" 在 Funktion ""public: virtual bool __thiscall MenuScreen::init(void)" (?init@MenuScreen@@UAE_NXZ)"。

谁能帮助我,告诉我问题出在哪里?

【问题讨论】:

  • 你的问题不在于类型推导。您得到的是链接器错误。查看链接的问答

标签: c++ arrays templates c++11 parameters


【解决方案1】:

您的函数是一个模板,这意味着定义必须在实例化点可见。这意味着要么将你的定义移动到你的头文件中,要么为你期望出现的所有 N 值显式实例化它。如果您期望 N 始终小于 10 左右,这可能是实用的。否则,您需要将定义放在头文件中,以便在与正确的模板参数一起使用时对其进行实例化。

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 2021-06-16
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多