gpt4 book ai didi

C++ 模板函数别名作为可变模板参数

转载 作者:太空宇宙 更新时间:2023-11-04 13:13:56 24 4
gpt4 key购买 nike

我正在尝试创建一个模板,允许调用者指定他们自己的格式良好的分配方法,但我在传递可变参数模板参数时遇到了问题。

如果我不传递任何参数,一切都会按预期进行;然而,如果我传递一个或多个参数,我会得到一个编译错误“函数调用的参数太多”。

我做错了什么?

#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);
}

另请注意,我也在 allocator 中使用了 make_unique,但您可以制作一个接受指针来构造 unique_ptr 的版本 与。

Live DEMO here

关于C++ 模板函数别名作为可变模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com