We help IT Professionals succeed at work.

Array of Type

williamcampbell
on
407 Views
Last Modified: 2012-05-07
I would like to have an array like this:

Hypothetical PseudoCode

struct mystruct
{
      char* tag;
      T type;
};

Completely Wrong but want to set up a const array like this
  const SomeStruct[] = { ( "tag1", double), ("tag2", int), ("tag3", char*)};

 Any way to do this using templates?

 
Comment
Watch Question

evilrixSenior Software Engineer (Avast)
CERTIFIED EXPERT

Commented:
>> Any way to do this using templates?
Specifically what do you want to do with templates and why do you think that would give a better solution?

BTW: Template values can only be integral types (numeric integer values known at compile time but not real numbers like float or double) and whilst char * is a valid value parameter for a template you can't actually pass a "string" to instantiate it because the address of the string is not known until runtime.
Senior Software Engineer (Avast)
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Interesting read

      is something like below possible?

      template< class T>
      struct item
      {
            item (std::sting i) { tag=i; }
            std::string tag;
      };

      somearray = { new item<int> ( "tag1"), new item<double> ( "tag2") }

Author

Commented:
Heres the scenario:

  Coming over the wire will be random string tags and some data. Depending on what the tag name is, determine the type from a const array (or vector or whatever) and interpret the data.
CERTIFIED EXPERT
Top Expert 2009
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
evilrixSenior Software Engineer (Avast)
CERTIFIED EXPERT

Commented:
>> check your compiler for support, it might already be there
Any compiler that is TR1 ready will (should?) support this... but remember it is NOT portable until it is ratified.


Can't you just use a std::map? The key being the string tag and the value being whatever you need it to resolve to (a struct of const data or a polymorphic handler class for example)?

http://www.cplusplus.com/reference/stl/map/
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks guys lots to think about
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.