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

Time:06-08

I've the following code

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

CodePudding user response:

While you can do that, you may want to limit the possible types to subtypes of Person:

#include <concepts>
#include <string>

struct Person {
    std::string first_name;
    std::string last_name;
};

struct Employee : Person {
    std::string position = "Manager";
};

template <std::derived_from<Person> P>
struct A {
    P p;

    A() {
        p.first_name = "John";
        p.last_name = "Smith";
    }
};

int main() {
    A<Person> ap; // works
    A<Employee> ae; // works
}

See online

  • Related