简体   繁体   English

C ++:用户定义类型的向量?

[英]c++: vector of user-defined type?

I have a vector that I'm storing data in. I want users to be able to decide the level of precision for the storage vector (either floats or doubles). 我有一个要在其中存储数据的向量。我希望用户能够确定存储向量的精度级别(浮点数或双精度数)。

How do I declare a vector based on user input? 如何根据用户输入声明向量? This obviously doesn't work: 这显然行不通:

std::vector<userWantsFloats ? float : double> data; ...

You cannot choose the type used in a class template instantiation based on a value that is known only at run time. 您不能基于仅在运行时知道的值来选择用于类模板实例化的类型。

Use of 用于

std::vector<userWantsFloats ? float : double> data;

is OK if the value of userWantsFloats is known at compile time. 如果在编译时知道userWantsFloats的值, userWantsFloats OK。 It is not OK if the value of userWantsFloats is not known only at run time. 如果仅在运行时不知道userWantsFloats的值, userWantsFloats

You'll have to use something along the lines of: 您必须按照以下方式使用某些东西:

if ( userWantsFloats )
{
   std::vector<float> data;
   // Use data
}
else
{
   std::vector<double> data;
   // Use data
}

To be able to maximize reuse of rest of your code, they have to be function templates and/or class templates. 为了最大程度地重用其余代码,它们必须是函数模板和/或类模板。

template <typename T>
void myAppLogic(std::vector<T>& data)
{
   // Do the work of your application
}

if ( userWantsFloats )
{
   std::vector<float> data;
   myAppLogic(data);
}
else
{
   std::vector<double> data;
   myAppLogic(data);
}

A option could be to use a std::variant . 一个选项可能是使用std::variant

std::variant<std::vector<float>, std::vector<double>> data;

You then initialize the variant based on user input, but can write any logic only once by using std::visit 然后,您可以根据用户输入来初始化变量,但是只能使用std::visit编写一次逻辑

std::visit([](auto&& vec) {
  // Do your thing
}, data);

If C++17 is not an option, then boost has a variant template that inspired the now standard one. 如果不能选择C ++ 17,则boost具有一个启发了现在标准模板的变体模板。 You can use that instead. 您可以改用它。 Consult the boost documentation on the subject. 请查阅有关该主题的增强文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM