是否可以将类作为参数传递给c++中的函数

Is it possible to pass a class as a parameter to a function in c++?

本文关键字:c++ 函数 参数传递 是否      更新时间:2023-10-16

我有一个函数,它的参数之一是void*(void用作泛型对象)。但是,为了能够调用该泛型对象中的函数,我需要首先对其进行强制转换,为此我需要知道类的类型。我想知道,是否可以传递一个类或一些信息,使我能够将对象强制转换为函数参数?

您有没有研究过Templates?

例如

class SomeClass
{
public:
    template<typename CastClass>
    void DoSomething(void* someArg)
    {
         (CastClass)someArg;
    }
};

用法:

class A{ }; // Some random test class
SomeClass test;
A a;
test.DoSomething<int>(&a); // The template parameter can be anything. 
                           // I just have int to make it a smaller example.