C++模板函数别名为可变参数模板参数
C++ template function aliases as variadic template arguments
我正在尝试创建一个模板,允许调用方指定自己的格式良好的分配方法,但是我在传递可变参数模板参数时遇到问题。
如果我不传递任何参数,一切都按预期工作;但是,如果我传递一个或多个参数,我会收到编译错误"函数调用的参数太多"。
我做错了什么?
#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("%dn", *up1);
printf("%dn", *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("%dn", *up0);
printf("%dn", *up0b);
printf("%dn", *up0c);
printf("%dn", *up1);
printf("%dn", *up1b);
printf("%dn", *up1c);
}
另请注意,我也在allocator
中使用make_unique
,但您可以制作一个接受指针的版本来构造unique_ptr
。
现场演示在这里
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 正在将动态数组元素解析为参数?(变音符)