0

I have created the struct

struct Event
{
  int key;
  boost::variant<int, float> value;
};

Is it possible to create Events like so:

Event e;

I have tried this but am getting compiler errors. Is this possible or do i HAVE to do:

Event e = new Event();

*EDIT: * This is the error im getting: error C2061: syntax error : identifier 'storage_' (in variant.hpp)

There are some comments here in variant.hpp but i cant make sense of them, as the "first-bound type is an int???

    // NOTE TO USER :
    // Compile error from here indicates that the first bound
    // type is not default-constructible, and so variant cannot
    // support its own default-construction.
    //
Stoff81
  • 597
  • 4
  • 15
  • 1
    there is no difference. however your first alleged code would not compile due to lacking semicolons, and after fixing that the code does not exemplify the alleged problem. do post **real code**, and complete example!, for we are not telepaths and can't see what you see on your screen – Cheers and hth. - Alf Apr 12 '13 at 02:20
  • yeah that was dumb of me. EDITED. – Stoff81 Apr 12 '13 at 02:22
  • 1
    You're not showing real code, nor the error message, so it's hard to diagnose your problem. For example, `Event` needs a `struct` or `class` keyword and semicolon after `key`, and `Event e = new Event()` won't compile... you need `Event* idn = new Event();`. There's no evident reason to need to use `new` if your actual code didn't have a mistake in it. – Tony Delroy Apr 12 '13 at 02:23

2 Answers2

1

Yes, it is possible. One of the examples in the doc (http://www.boost.org/doc/libs/1_53_0/doc/html/variant/tutorial.html) is:

boost::variant< int, std::string > v;

which it states does:

By default, a variant default-constructs its first bounded type, so v initially contains int(0). If this is not desired, or if the first bounded type is not default-constructible, a variant can be constructed directly from any value convertible to one of its bounded types"

Barry
  • 286,269
  • 29
  • 621
  • 977
  • I saw you struggling in your edits with the quote: use blockquote instead of code sample, and it will format nicely. – JBentley Apr 12 '13 at 02:27
  • @JBentley Cheers! That is way better :) I've seen people do it before, I guess now I know how – Barry Apr 12 '13 at 02:36
1

The following compiles for me (VS2012):

#include "boost/variant.hpp"

struct Event
{
  int key;
  boost::variant<int, float> value;
};

int main()
{
   Event e;
   return 0;
}

So, yes, it is possible to create it without new. If you want further help, I'd suggest showing the complete code which demonstrates the problem, as well as the compiler error message.

JBentley
  • 6,099
  • 5
  • 37
  • 72
  • This compiles for me too in a seperate project. There must be something funky with my main project as to why im getting the error above. Will post back after some investigation. – Stoff81 Apr 12 '13 at 02:33