Home > front end >  How to get type of template of class from its object in C
How to get type of template of class from its object in C

Time:10-28

I have a custom class A and want to get the type of template from the code which initialized an object of A class to use it as a variable later. Is that possible?

#include <functional>

template<class T>
class A {
public:
    A(){};
    T data;
};

int main() {
    A<int> a;

    // How to get int as type?
    // function <void (type)> foo;
    return 0;
}

CodePudding user response:

If you would like the template type to be discoverable by code, you can make a public using to expose it:

template<class T>
class A {
public:
    using type = T;  // <<<< add this (or something like it)

    A(){};
    T data;
};

Then in main

int main() { // side note: main() *must* return an int
    using AI = A<int>;
    AI a;
   
    function <void (AI::type)> foo;
}

[Edited to match your question that changed after this was posted.]

  •  Tags:  
  • c
  • Related