Ein Herjar
Ein Herjar

Reputation: 3

Type trait for extracting template parameter from nested type

I need to get the template parameter from a nested type. Here is a simple example to show the type I need to extract.

#include <iostream>
#include <typeinfo>

template<typename T>
void function(T) {
    // T = 'struct A<int>::B'
    //
    // Here I want to get the template value type e.g. 'int' from T
    // so that this would print 'int'. How can this be done?        
    std::cout << typeid(T).name() << std::endl; 
}

template<typename T>
struct A { 
    using B = struct { int f; };
};

int main() {
    function(A<int>::B{});
    return 0;
}

Upvotes: 0

Views: 374

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

You can't extract this through simple deduction. Although B is a nested class of A, the types themselves are unrelated.

One option would be to "save" the type inside B and extract it later:

template<typename T>
struct A { 
    struct B { 
        using outer = T; 
        int f; 
    };
};

Then you just use typename T::outer to get the type:

template<typename T>
void function(T) {     
    std::cout << typeid(typename T::outer).name() << std::endl; 
}

Upvotes: 2

Related Questions