【问题标题】:Why cannot I use an instantiation of std::make_shared as a pointer to function?为什么我不能使用 std::make_shared 的实例作为函数指针?
【发布时间】:2014-02-10 10:47:18
【问题描述】:

当一个类有一个默认构造函数时,我可以使用std::make_shared 的实例化,就像指向函数的指针一样。这可能是因为实例化的模板必须经过编译并存储在内存中,并且它的地址必须存在。

#include <memory>
#include <functional>

class DefaultConstructible
{
};

typedef std::function<std::shared_ptr<DefaultConstructible>()> Generator;

int main()
{
    Generator generator(std::make_shared<DefaultConstructible>);
    std::shared_ptr<DefaultConstructible> defConst = generator();

    return 0;
}

但是当我添加一个重要的构造函数时同样的事情失败了:

#include <memory>
#include <functional>

class FromInt
{
public:
    FromInt(int a):a_(a){}
    int a_;
};

typedef std::function<std::shared_ptr<FromInt>(int)> Generator;

int main()
{
    Generator generator(std::make_shared<FromInt>);
    std::shared_ptr<FromInt> p = generator(2);

    return 0;
}

我得到一个编译器错误:

 error: no matching function for call to 
'std::function<std::shared_ptr<FromInt>(int)>::function(<unresolved overloaded function type>)'
     Generator g(std::make_shared<FromInt>);
                                          ^

为什么会这样?如何编译我的代码?

【问题讨论】:

    标签: c++ templates c++11 c++-standard-library


    【解决方案1】:

    您只需要明确说明您希望它使用哪个构造函数:

    Generator generator(std::make_shared<FromInt, int>);
    

    “额外”模板参数对应于构造函数参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      相关资源
      最近更新 更多