【问题标题】:Why Universal Reference concept not working for map insert in case of function pointers为什么通用参考概念在函数指针的情况下不适用于地图插入
【发布时间】:2018-04-20 07:40:23
【问题描述】:

如果我不明确使用 std::pair 和 map insert ,有人可以解释为什么下面的代码不起作用:

#include <iostream>
#include <string>
#include <map>
#include <memory>
typedef std::shared_ptr<int>(*CreatorFunction)();
std::shared_ptr<int> test()
{
    std::shared_ptr<int> p(new int);
    return p;
}
int main()
{
  std::map<int, CreatorFunction> tmap; 
  tmap.insert(1,test); //this doesn't work
  tmap.insert(std::pair<int,CreatorFunction>(1,test)); //this works
 return 0;
}

我的理解是在 c++14 中我们不需要使用 std::pair 因为插入函数定义已更改为接受通用引用,如下所示:

template <class P> pair<iterator,bool> insert (P&& val);

【问题讨论】:

  • 重载需要一个参数。你过了两个。它不可能被选中。
  • @Matt,对不起。有什么办法可以删除这个问题
  • 如果你坚持的话,标签下应该有一个“删除”链接。

标签: c++ stl c++14 forwarding-reference


【解决方案1】:

std::map::insert 中没有任何重载需要两个参数,您应该使用 std::make_pair。见下面的sn-p

#include <iostream>
#include <string>
#include <map>
#include <memory>

#include <functional> // for std::function.

// typedef std::shared_ptr<int>(*CreatorFunction)();
typedef std::function<std::shared_ptr<int>()> CreatorFunction; // The c++ way.

// Take a look at this function. std::shared_ptr<int> will automatically destroy the int* and might result in undefined.
std::shared_ptr<int> test()
{
    std::shared_ptr<int> p(new int);
    return p;
}
int main()
{
    std::map<int, CreatorFunction> tmap; 
    tmap.insert(std::make_pair(1,test)); // edited this line
    tmap.insert(std::pair<int,CreatorFunction>(1,test)); // this works
    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多