Joseph Park
Joseph Park

Reputation: 53

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

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?

Upvotes: 1

Views: 93

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

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

Remind yourself though that the template must be implemented in the header files. The compiler has to have access to implementation to instantiate the templates.

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

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

Upvotes: 0

Related Questions