Simon Parker
Simon Parker

Reputation: 1834

Getting the type of a variable in a template

This was initially spawned by trying to extract the type from a unique_ptr, which turned out to be easy. However, I am now interested in the general case.

Here's what I am looking for:

template<class CHILDOBJ>
void MyChildFunc()
{
    // do stuff with the CHILDOBJ type
};

template<class OBJTYPE>
void MyFunc(OBJTYPE obj)
{
   MyChildFunc<TYPE of OBJTYPE::child????>();
};

struct MyIntStruct
{
    int child;
};

struct MyDoubleStruct
{
    double child;
};

void main(void)
{
    MyIntStruct int_struct;
    MyDoubleStruct double_struct;

    MyFunc(int_struct);
    MyFunc(double_struct);
}

So I want a way of calling MyChildFunc using the type of an attribute from the object passed in to MyFunc. I know I can create another template function, and pass obj.child to it to allow deduction, but I was hoping for a way to deduce the type manually, and use that in the template argument directly.

As I said, this is now more academic than real, which is why the code is so contrived, but I am interested to know if there is a way to do it.

Upvotes: 0

Views: 128

Answers (1)

AhiyaHiya
AhiyaHiya

Reputation: 755

How's this:

template<class CHILDOBJ>
void MyChildFunc()
{
    // do stuff with the CHILDOBJ type
};

template<class OBJTYPE>
void MyFunc(OBJTYPE obj)
{
    MyChildFunc<decltype(OBJTYPE::child) >();
};

struct MyIntStruct
{
    int child;
};

struct MyDoubleStruct
{
    double child;
};


int main(int argc, const char * argv[])
{
    MyIntStruct int_struct;
    MyDoubleStruct double_struct;

    MyFunc(int_struct);
    MyFunc(double_struct);
    return 0;
}

I compiled this with Xcode 6 and it seems to work as desired.

Upvotes: 2

Related Questions