I want to pass the class type to the function argument

Asked 1 years ago, Updated 1 years ago, 259 views

classBaseClass{
    // member variable
    // member function
};

class FirstClass:public BaseClass {
};

classSecondClass:publicBaseClass{
};

classThirdClass:publicBaseClass{
};
void func()
{
    autoptr=std::make_shared<CLASS_NAME>;
}

int main(intargc, char*argv[])
{
    func(CLASS_NAME); // either FirstClass, SecondClass, or ThirdClass
}

When a class is defined as above, I would like to make_shared any object in the func function by specifying the type of class as an argument for the func function from the main function. How should I design the func function?

c++

2023-01-25 16:51

1 Answers

As a template function, should I receive type arguments instead of arguments?

template<class ClassName>
void func(){
    autoptr=std::make_shared<ClassName>();
}

int main() {
    func<FirstClass>();
}

If you really want to write in parentheses, you can do it by adding macro definitions.

#defineFUNC(CLASS_NAME) func<CLASS_NAME>()

int main() {
    FUNC (FirstClass);
}


2023-01-25 17:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.