我正在尝试编写以下工厂类,但找不到正确的语法:
template<class T, typename... TArgs>
class Factory {
public:
Factory(TArgs... args) {
creator_ = std::bind(&std::make_shared<T, TArgs...>, args...);
// ^^^ some error around here
}
std::shared_ptr<T> Create() const {
return creator_();
}
private:
std::function<std::shared_ptr<T>()> creator_;
};
这就是我使用工厂的方式:
class Foo {
public:
Foo(bool value) {}
};
class Bar {
public:
Bar(const std::string& value) {}
};
Factory<Foo, bool> f1(true);
Factory<Bar, std::string> f2("string");
这些是我在声明时遇到的错误f1
and f2
:
error: no match for 'operator=' (operand types are 'std::function<std::shared_ptr<Foo>()>' and 'std::_Bind_helper<false, std::shared_ptr<Foo> (*)(bool&&), bool&>::type {aka std::_Bind<std::shared_ptr<Foo> (*(bool))(bool&&)>}')
creator_ = std::bind(&std::make_shared<T, TArgs...>, args...);
^
error: no match for 'operator=' (operand types are 'std::function<std::shared_ptr<Bar>()>' and 'std::_Bind_helper<false, std::shared_ptr<Bar> (*)(std::basic_string<char>&&), std::basic_string<char, std::char_traits<char>, std::allocator<char> >&>::type {aka std::_Bind<std::shared_ptr<Bar> (*(std::basic_string<char>))(std::basic_string<char>&&)>}')
creator_ = std::bind(&std::make_shared<T, TArgs...>, args...);
^
我必须使用的正确语法是什么std::bind
?