user3375989
user3375989

Reputation: 25

Can I access a struct passed into a template generically?

As per the title, this is what I am looking to do. Basically I am looking to load in structures from files, but support every kind of structure, so I am attempting to do it in a template. This is my first time using templates really so excuse my ignorance!

I want to be able to do something like:

template<class T> T ConfigLoader::LoadStructFromFile(T a)
{
    int noOfThingsInStruct;
    noOfThingsInStruct = a[1];
    return a;
}

Is this at all possible? My function does sorting of the string loaded in from files etc but thought I would leave that part out. I want to be able to get this value to use it to loop and give the struct the correct number of values it is looking for.

Upvotes: 0

Views: 116

Answers (2)

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

Simple answer: impossible.

Long answer: still no.

Detour:

  • you can use something based on type traits. Create a template class numberOfElements<typename T> and overload it for every struct you need with a value you expect. Then, use it in your LoadStructFromFile, since you know T.
  • You can also use SFINAE to test for some function that'll return the number of elements in a struct. If a given class/struct implements it, just use it to get the number of members. If not - assume there's only 1 member (or whatever you wish).

Upvotes: 0

David
David

Reputation: 28178

So you want to dynamically figure out what members and methods are in a struct? Similar to, say, what you can do in Javascript in runtime, but in compile time? No, you can't. However, you can make a template policy and base this function on that.

Upvotes: 1

Related Questions