【发布时间】:2016-11-18 00:37:54
【问题描述】:
我正在尝试创建一个模板,允许调用者指定他们自己的格式良好的分配方法,但我在传递可变参数模板参数时遇到问题。
如果我不传递任何参数,一切都会按预期进行;但是,如果我传递一个或多个参数,我会收到一个编译错误“函数调用的参数太多”。
我做错了什么?
#include <cstdio>
#include <memory>
template <typename T, typename... Args>
using allocator = std::unique_ptr<T>(Args...);
template <typename T, allocator<T> A, typename... Args>
std::unique_ptr<T> get(Args... args) {
return A(args...);
}
int main() {
auto up1 = get<int, std::make_unique<int>>(); // Works
auto up2 = get<int, std::make_unique<int>>(1); // Too many arguments
// expected 0, have 1
printf("%d\n", *up1);
printf("%d\n", *up2);
}
【问题讨论】:
-
This 工作,但这真的是你想要的界面吗..?这对我来说就像一个XY problem。
-
我可能会重构以更改界面,但我仍然有兴趣了解潜在问题。为什么在这种情况下可变参数不能与模板别名一起使用?
-
allocator<T>是allocator<T, empty-pack>这是std::unique_ptr<T>()然后调整为std::unique_ptr<T> (*)()。 -
有道理,T.C.是否可以以这样的方式定义模板,以便分配器可以使用可变参数?我不能做 allocator
因为模板参数是在可变参数 Args 参数之前定义的。
标签: c++ c++14 variadic-templates