user2750198
user2750198

Reputation: 1

Passing structure to a template function in C++

This is what i want to achieve,

  1. I want to pass structure as an argument to a function, which will return character pointer
  2. Everytime i will pass different structure as argument, which has distinct name and member variables of different types
  3. The function has to identify the structure and its member variables, get the value of the member variable and concatenate it as a single string and return.

Please suggest....

am confused with template function and RTTI.....

Upvotes: 0

Views: 198

Answers (4)

Manu343726
Manu343726

Reputation: 14184

Why you don't represent your structs (Which have same memeber types, but different names) as tuples?. IMHO if you want to treat this set of structs in the same manner, having different names is counterproductive:

template<typename...Ts>
void f(const std::tuple<Ts...>& tuple)
{
    ...
}

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254691

There's no particularly nice way to iterate over class members. One approach I've used is to store the values in a tuple, and provide named accessors if required:

struct a {
    std::tuple<int, char*> stuff;
    int  & x() {return std::get<0>(stuff);}
    char & y() {return std::get<1>(stuff);}
};

In the future (next year, perhaps?) we should get type deduction for function return types (as we already have for lambdas), which will remove error-prone type specifier in each accessor.

You can then use variadic template functions to iterate over the tuples.

Upvotes: 0

Sebastian Redl
Sebastian Redl

Reputation: 72054

You could look into Boost.Fusion, in particular BOOST_FUSION_ADAPT_STRUCT.

Upvotes: 3

nickie
nickie

Reputation: 5818

The first suggestion that crosses my mind is: redesign!

If you really want to do it like you say and don't know the names of the fields, I don't think a template will do you any good. I'd suggest using the preprocessor:

#define UGLY(str, int_field, char_field) whatever_you_want_to_do_with_them

and then you'd call:

a some_a;
b some_b;

UGLY(some_a, x, y);
UGLY(some_b, b, a);

Upvotes: 1

Related Questions