c++ - 在 C++ 中将映射传递给模板函数时出错

标签 c++ templates

我一直在用头撞砖墙,决定提交并发布我的错误。

我有一个传递 std::map 的模板(如下所示),它位于命名空间内。这编译得很好。

我的问题发生在尝试调用函数模板时。我收到以下错误:

error: no matching function for call to 
    'getValuePointer(Muon*&, std::map<int, MET*, std::less<int>, 
                     std::allocator<std::pair<const int, MET*> > >*&)'

我做错了什么?

模板代码如下:

#ifndef OBJECTMAPMATCH_H
#define OBJECTMAPMATCH_H

#include <map>
#include <utility>
#include <typeinfo>
#include <iostream>
#include <stdlib.h>

using namespace std;

namespace ObjectMapMatch {


  template< class A, class B, class C >
    C  getValuePointer( A &x , map< B,C> &y )
  {

    if( y.find(x.Index()) != y.end() ){

      return y.find(x.Index()).second;

    }else{
      cout << "ERROR:ObjectMapMatch::getValuePointer:Can not Find " 
           <<  typeid(y).name() << " FOR " << typeid(x).name() << endl;
      exit(1);
    }

  }

}
#endif

这里是调用模板函数的例子

C = ObjectMapMatch::getValuePointer<ClassC*, int, ClassD*>(A, B);

地点:

C is ClassC*
A is ClassC*
B is std::map<int,ClassD*>*  

我做错了什么?

最佳答案

根据错误消息,您将指向 map 的指针作为第二个参数传递,而该函数需要对 map 的引用。

你可以看到这个是因为结尾处的 *:

no matching function for call to 
    'getValuePointer(Muon*&, std::map<...>*&)'
                                          ^

一旦你解决了这个问题就会有额外的问题:因为 xClassC* 类型,调用 x.Index() 将报错。也许第一个模板参数应该是 ClassC 而不是 ClassC*

关于c++ - 在 C++ 中将映射传递给模板函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8327393/

相关文章:

c++ - 指向带有空格的字符串的指针

c++ - 如何修复 C++ 中的 int-to-bool 警告?

javascript - 在 JQuery 模板中调用 javascript 函数

c++ - 为类方法创建模板

ios - ios应用需要什么样的模板

c++ - C++余弦查找表

c++ - 如何反转 `std::integer_sequence<int, 4, -5, 7, -3>` 中整数的顺序?

c++ - 为什么 NULL 被转换成 string*?

c++ - 带有 ssl 本地证书的 QNetworkRequest

c++ - 成员模板静态函数的类型特征