【发布时间】: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