【发布时间】:2021-10-10 06:06:44
【问题描述】:
谁能告诉我为什么我可以只用一个模板参数调用std::make_unique<S>,即S,像这样:
auto p = std::make_unique<S>(12, 13);
但是,我不能将 std::make_unique<S> 传递给一个函数来为我执行此操作,如下所示:
template <typename FuncType, typename ...Args >
void call_method(FuncType f, Args... args)
{
f(std::forward<Args>(args)...);
}
struct S
{
S(int x, int y) {}
};
int main()
{
call_method(std::make_unique<S>, 12, 13); // not working
// call_method(std::make_unique<S, int , int>, 12, 13); // works fine
return 0;
}
编译器显示的错误是:
Error C2512 'S::S': no appropriate default constructor available.
我正在 Windows 10 上使用 Visual Studio 2017。
【问题讨论】:
-
一个解决方案是通过
[](auto &&... args) { return std::make_unique<S>(decltype(args)(args)...); }。 -
顺便说一句,
Args... args不启用转发。 -
@StoryTeller-UnslanderMonica 声明
Args&& ...args将启用转发可能是个好主意 -
@Const 这是一个显示示例的简单代码。在实际代码中,我必须重用一个现有的方法,比如
call_method。
标签: c++ c++11 templates unique-ptr