1
我试图创建一个模板,它允许调用者指定自己的格式良好的分配方法,但我遇到了传递可变参数模板参数的问题。C++模板函数别名作为可变参数模板参数
如果我不通过任何参数,一切都按预期工作;但是,如果我传递一个或多个参数,则会出现编译错误“函数调用的参数太多”。
我在做什么错?
#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);
}
[这](http://coliru.stacked-crooked.com/a/cd68dec6691d5323)_works_,但是这真的是你想要的界面..?这对我来说似乎是[XY问题](http://meta.stackexchange.com/a/66378/166663)。 – ildjarn
我可能会重构来更改界面,但我仍然对理解底层问题很感兴趣。为什么可变参数在这种情况下不适用于模板别名? –
'allocator'是'allocator ,它是'std :: unique_ptr ()',然后调整为'std :: unique_ptr (*)()'。 –