0

I am working on a modular data logger that allows one to log data of different types. At the moment I made a File class that is a template. In order to declare an object of such a class one would do as such: File<double> f("filename.txt") or File<float> f("filename.txt"). I want to be able to store objects that were declared with double or float as template parameters in one vector. Is it possible to do something like that? I have tried a method online that uses a union as such:

union typ {
    int int_dat;
    double double_dat;
    float float_dat;
}  

and allows me to declare a vector as such: vector<File<typ> >. However, this gives me linker errors. Is there a easier, cleaner way to attempt this? The entire project in question is here

EDIT: follow up to this. How would one circumvent the issue surrounding the fact that if I conduct such operations:

std::vector<File<typ> > files;

File<typ> f("test.txt");
files.push_back(f);
files.at(0) << 35.4;

it causes a compile time error which I comprehended as what I'm guessing is: 35.4 is not of the type typ and cannot be used in the operation <<. How would one bypass such an error?

swarajd
  • 977
  • 1
  • 10
  • 18

3 Answers3

1

I think your vector of unions might have some issues. I haven't looked at your full code, but refer to this:

Questions about vector, union, and pointers in C++

Community
  • 1
  • 1
Joshua
  • 328
  • 1
  • 7
1

The following should work (see http://codepad.org/TyrURyar)

#include <vector>

union type {
    int int_dat;
    double double_dat;
    float float_dat;
};

template <typename T>
class Foo {
    T t;
};

void foo2() {
    std::vector<Foo<type> >  x;    
    // NOTE: In pre-C++11, space is required between the >'s
}
Arun
  • 19,750
  • 10
  • 51
  • 60
  • Thank you! I screwed around a bit with my code, and it turns out that it was actually a problem with my destructor. weird. Thanks again! – swarajd Apr 01 '14 at 23:32
1

Use Boost::Variant, if you can. It's a cleaner option. Unions can be used, but you should write and read from the same member if you don't want to end up with undefined behaviour i.e. it involves book keeping, which anyways Variant does for you automatically.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • I do not usually use Boost... but... it is probably the more efficient option if you are dealing with a lot of data. – Joshua Apr 01 '14 at 23:35
  • I would use this, but I have a small amount of memory to work with, so I do not have the liberty to use external libraries. – swarajd Apr 01 '14 at 23:48