Home > OS >  Is there a way to get the methods of a class if you send class as <T>? C
Is there a way to get the methods of a class if you send class as <T>? C

Time:06-08

So I have a code like that is like this

class Person{
public:
    string fname, lname;
    string getName(){
        return fname   " "   lname;
    }
}
 
template<class T> class A{
    ...
}

int main(){
    A<Person>* a = new A<Person>();
}

Since for template class A, I have T saved as Person is there any way I can use the methods and variable in the Person class? Like,

template<class T> class A{
public:
    A(){
        T* person = new T();
        person->fname = "John";
        person->lname = "Doe";
    }
}

Is there some way something like this could be done?

CodePudding user response:

Have you tried? I see no problem with this code. Templates are not like Java's generics, you can use the types directly as if it was normal code.

#include <string>
#include <iostream>

class Person{
public:
    std::string fname, lname;
    std::string getName(){
        return fname   " "   lname;
    }
};

template<class T> class A{
public:
    A(){
        T person = T();
        person.fname = "John";
        person.lname = "Doe";
        std::cout << person.fname << " " << person.lname << "\n";
    }
};

int main(){
    A<Person> a = A<Person>();
}

Output:

John Doe

Live example

  • Related