P
Peter Olcott
Its like I am making my own VARIANT record. I need some features that VARIANTJim Langston said:Jim Langston said:Peter Olcott wrote:
Peter Olcott wrote:
If all that I want is std::string could I simply use [ std::string*
String ] in my union?
You would need management code to allocate and deallocate it.
I already figured that, are there any other issues?
You need to remember which element you stored in the vector.
Once you do all that you probably have reimplemented boost::any.
Okay then this is the way that I will do it.
It depends on what you are actually tryign to do. A union of a double and a
pointer doesn't seem like it will do you any good. It sounds more like you
want to refer to this double as either a double, or as a std::string,
correct? It would seem a simple class would work for you. Something like:
#include <iostream>
#include <string>
#include <sstream>
class AnyType
{
public:
operator double() const { return Val_; }
operator std::string () const
{
std::stringstream Convert;
Convert << Val_;
return Convert.str();
}
AnyType* operator= ( const double Val ) { Val_ = Val; return this; }
AnyType* operator= ( const std::string& Val )
{
std::stringstream Convert;
Convert << Val;
Convert >> Val_;
return this;
}
private:
double Val_;
};
int main()
{
AnyType MyDouble;
MyDouble = 1234.56;
std::cout << MyDouble << "\n";
MyDouble = "2345.67";
std::cout << MyDouble << "\n";
std::string wait;
std::getline( std::cin, wait );
}
This could easily be converted to a template for any type.
Is this the kind of thing you are looking for?
Peter Olcott said:I can't tell what you are trying to do here, but, the std::string will
probably not hold data that can be converted to and from string.
Please don't top post. Message rearranged.
You mean not hold data that can be converted to and from a double?
Okay, so you want your union to hold *either* a std::string or a double. There
are a few ways to do this including templates, templates with common base
class, pointers, etc...
How is it you want to be able to use AnyType?
does not have.