Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading