gpt4 book ai didi

c++ - 可变参数模板方法来创建对象

转载 作者:行者123 更新时间:2023-12-04 12:27:21 24 4
gpt4 key购买 nike

我在模板类(类型 T_)中有一个可变参数模板方法,如下所示

template < typename T_ >
class MyContainer {
public:

...
template <typename ...A>
ulong add (A &&...args)
{
T_ t{args...};
// other stuff ...
vec.push_back(t);
// returning an ulong
}
}
所以基本上我试图让这个类适应任何类型 T_但由于我无法事先知道其构造函数需要哪些类型,因此我使用了可变参数。我从 emplace_back 中获得灵感来自 STL 库的方法。
尽管如此,如果我尝试做这样的事情,我会收到缩小整数类型转换的警告
MyContainer<SomeClassRequiringAnUlong> mc;
mc.add(2);
warning: narrowing conversion of ‘args#0’ from ‘int’ to ‘long unsigned int’ [-Wnarrowing]
所以我想知道我是否可以做些什么。有什么方法可以根据模板参数 T_告诉方法它应该采用哪种参数类型(这是在创建对象时已知的)?

最佳答案

Is there any way to tell the method which parameters' type it issupposed to take according to the template parameter T_ (which isknown when the object is created)?


在您的情况下,您应该使用直接初始化( () )而不是列表初始化( {} )(以避免不必要的缩小检查)。
考虑 T 的情况是 vector<int> :
MyContainer<std::vector<int>> mc;
mc.add(3, 0);
你有什么期望 mc.add(3, 0)去做?在您的 add()功能, T_ t{args...}将调用 vector<int>{3,0}并创建一个 vector大小为 2,这显然是错误的。您应该使用 T_ t(args...)调用 vector(size_type count, const T& value) 的重载构造一个大小为 3 的 vector ,就像 emplace_back() 做。
值得注意的是,由于 P0960R3 , T_ t(std::forward<Args>(args)...)如果 T_ 也可以执行聚合初始化是聚合。

关于c++ - 可变参数模板方法来创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69720667/

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