将不同类型的模板参数包提取到双精度向量中会产生警告
extracting a template parameter pack with different types into a vector of doubles produces warnings
我正在尝试将基本相同但采用不同数量的参数的类负载转换为单个模板类。所以我创建了一个模板类示例(不是真正的代码 - 只是例如(:
// The template type
template<typename... Args>
class tester_template
{
public:
void process(Args... args)
{
// Create a vector to put the args into. use double since that can hold all of the types
// that I am using (well enough for me anyway). But I get a lot of "narrowing" warnings
// this is understandable, but I want to have no warnings (some sort of cast on a
// parameter pack??)
std::vector<double> args_vect = {args...};
for (auto arg : args_vect)
{
std::cout << arg << " ";
}
std::cout << std::endl;
};
};
我像这样运行:
// Same with one template class
tester_template<double> template1;
tester_template<int, int> template2;
tester_template<int, int, int> template3;
tester_template<float> template4;
tester_template<float, double, int> template5;
template1.process(1.123); // ok
template2.process(2, 2); // Warnings
template3.process(3, 2, 3); // Warnings
template4.process(4.4f); // Warnings
template5.process(5.5f, 2.234, 3); // Warnings
此处的完整示例包含警告以及模板类替换的前许多类的示例:https://rextester.com/RBEA68379
所以我理解错误/警告消息(基本上如果我转换,我可能会丢失数据(。但我想抑制警告——也许通过投射。但是我不知道如何使用参数包执行此操作 - 也许我错过了它,但我没有在网上找到它。
我猜有两个问题:
- 我可以抛弃(或其他不关闭警告的方法(吗? 我
- 只是想将参数包提取到我可以迭代的结构中,我正在做的事情是明智的,还是有更好的方法?
是的,您可以轻松转换参数:
std::vector<double> args_vect = {static_cast<double>(args)...};
并且没有发出警告。
这是一个演示。
正如@NathanOliver在评论中指出的那样,如果您只想打印所有可变参数,您可以执行以下操作:
void process(Args... args)
{
((std::cout << args << " "), ...);
std::cout << std::endl;
};
然后,您不必担心任何类型的转换。
这是一个演示。
您还可以使用sizeof...
来确定传入的参数数,并使用该信息调度到采用固定数量参数的函数:
void process1arg(double ) {}
void process2arg(double , double ) {}
void process3arg(double , double , double ) {}
void process(Args... args)
{
((std::cout << args << " "), ...);
std::cout << std::endl;
if constexpr (sizeof...(args) == 1)
process1arg(args...);
if constexpr (sizeof...(args) == 2)
process2arg(args...);
if constexpr (sizeof...(args) == 3)
process3arg(args...);
};
请注意,您需要if constexpr
而不是常规if
,否则当参数数量不匹配时,代码将无法编译。
这是一个演示。
相关文章:
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 从.txt文件读取到C++中的双精度向量
- C++ 运算符"="重载 - 在 lhs 上获取向量中的所有值,使其等于 rhs 上的双精度值
- 使用整数初始化列表初始化长双精度的向量
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 向量<对<双精度,双精度>>给出问题
- 获取长双精度向量的方差
- 如何将 4 个浮点数的 ps 向量转换为 4 个双精度并存储到 pd 数组
- 双精度/整数模板函数的向量
- 模板:如何泛化输入以接收整数、双精度或特定(模板)容器的向量
- 如何从二进制文件中读取双精度并将其保存在向量中
- C++在向量中添加元素的双精度
- 对双精度和指针对的向量进行排序
- 通过更改代码格式来计算结构向量中包含的双精度变量的平均值的不同结果?
- 以最大性能将双精度的向量截断为单精度
- 将值存储到具有相同精度C++的双精度向量中
- 如何从双精度向量的向量访问数据
- 从十六进制数组读取双精度到向量
- C++ 将字符串向量转换为给定.dat文件中的双精度向量
- <double> 向量被转换为向量<双精度,分配器<double>>