我正在尝试创建一个模板,允许调用者指定自己的格式正确的分配方法,但是在传递可变参数模板参数时遇到问题。
如果我不传递任何参数,那么一切都会按预期进行。但是,如果我传递一个或多个参数,则会收到编译错误“函数调用过多的参数”。
我究竟做错了什么?
#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);
}
相反,您可以允许并推导可能有状态的函子A的类型。再加上几个括号,但很难弄错这个错误:
#include <cstdio>
#include <memory>
template <typename T>
struct allocator{
template<typename... Args>
auto operator()(Args&&... args) const {
return std::make_unique<T>(std::forward<Args>(args)...);
}
};
template <typename T, typename A = allocator<T>>
auto get(A a=A{}) {
return [a](auto... args){
return a(args...);
};
};
int main() {
auto up0 = get<int>()();
auto up1 = get<int>()(1);
auto up0b = get<int>(allocator<int>())();
auto up1b = get<int>(allocator<int>())(1);
auto up0c = get<int>([](auto ... args){ return std::make_unique<int>(args...); })();
auto up1c = get<int>([](auto ... args){ return std::make_unique<int>(args...); })(1);
printf("%d\n", *up0);
printf("%d\n", *up0b);
printf("%d\n", *up0c);
printf("%d\n", *up1);
printf("%d\n", *up1b);
printf("%d\n", *up1c);
}
还要注意,我make_unique
也使用in,allocator
但是您可以创建一个接受指针来构造unique_ptr
with的版本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句