简体   繁体   English

C ++未知变量类型。 我应该使用模板吗?

[英]C++ unknown variable type. Should I use template?

I'm trying to create a class that will parse a file in C++. 我正在尝试创建一个类,该类将解析C ++中的文件。 However the file is actually in 2 files, the header and the raw data. 但是,该文件实际上位于2个文件中,即标头和原始数据。

The header contains the data type of the raw data (it can be int, double, float, etc...). 标头包含原始数据的数据类型(可以是int,double,float等)。 I want to create a variable in my class that will store the raw data. 我想在我的班级中创建一个变量来存储原始数据。 The processing will be the same, no matter the data type. 无论数据类型如何,处理都是一样的。

Should I use a template to do this ? 我应该使用模板来执行此操作吗? Isn't it overkill to use a templated class for just 1 variable ? 仅对1个变量使用模板化类是不是矫kill过正?

Thank you. 谢谢。

What about using function overloading ? 使用函数重载呢? You said the processing is the same, so... I think you could. 您说处理是一样的,所以...我想可以。 I use them sometimes to do this kind of stuff. 有时我会用它们来做这种事情。

Example: 例:

Header.h 标头

class MyClass {
public:
    void function(int x);
    void function(double x);
    void function(string x);
    void function(char x);
};

The compiler will know what function to use, depending of the value that you are sending (passing) to it. 编译器将知道要使用的功能,具体取决于您要发送(传递)给它的值。

Templates could certainly help you here. 模板当然可以在这里为您提供帮助。 They offer a way to reduce repetition of that processing which you say is the same for all types. 它们提供了一种减少重复处理的方法,您说对于所有类型都是相同的。

Whether you "should" use them is of course a more difficult question, as is whether it's overkill - both are matters of opinions, but common use would suggest that the use of just one variable would not be the factor that would decide that. 当然,是否“应该”使用它们是一个更困难的问题,是否过高也是如此-两者都是意见问题,但是通常的使用表明仅使用一个变量将不会成为决定该问题的因素。

If the contents of the files containing different types need to be processed into the same container or if a file can contain more than one type, then maybe boost variant would be more suitable. 如果需要将包含不同类型的文件的内容处理到同一容器中,或者一个文件可以包含多个类型,那么boost变体可能会更合适。

Since you read the types from file, those types are known at runtime, but since the list of options is known at compile time you can check the type in the file and pass in the type. 由于您是从文件中读取类型的,因此这些类型在运行时是已知的,但是由于选项列表在编译时是已知的,因此您可以检查文件中的类型并传递该类型。

if(typeFromFile == headerValueForint)
{
    processFile<int>();
}
else if (typeFromFile == headerValueFordouble)
{
    processFile<double>();
}

However as all the types you list are numeric (and I wonder how the processing could really be the same if there's any other non-numeric types) you could decide to read all the values in as doubles - with suitable range checking. 但是,由于您列出的所有类型都是数字类型(并且我想知道如果存在其他任何非数字类型,处理的方式实际上是一样的),您可以决定将所有值都读为双精度-进行适当的范围检查。 It might take up more memory but the impact of that depends on what the processing actually involves. 它可能占用更多的内存,但是其影响取决于处理实际涉及的内容。

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

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