c++ - 为什么我不能使用 std::make_shared 的实例化作为指向函数的指针?

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

当类具有默认构造函数时,我可以使用 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>);
                                          ^

为什么会这样,我怎样才能编译我的代码?

最佳答案

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

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

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

关于c++ - 为什么我不能使用 std::make_shared 的实例化作为指向函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21675068/

相关文章:

C++无限和代码挂了?冷冻?我不知道

python - Django - 呈现为字符串无法加载 CSS

templates - Ext.form.ComboBox : Use template for displayField

c++ - lambda capture 是否支持可变模板参数

c++ - 模板代码中的统一初始化

c++ - 为什么 boost::thread 的析构函数分离可连接线程而不是像标准建议的那样调用 terminate()?

c++ - ARM GCC 交叉编译器 fedora 22

c++ - Char* 相关的内存泄漏

c++ - 如何在 C++ 的 lambda 函数中传递同名的局部变量和参数(使用 this 关键字)?

c++ - 错误 : Out-of-line constructor cannot have template arguments C++