如何有效地重载一个函数,而不会发疯

How to efficiently overload a function, without going insane?

本文关键字:函数 发疯 一个 有效地 重载      更新时间:2023-10-16

所以我有这个函数(它有80行):

int listPlatformInfo(..., char * foo)
{
    ... 
    for (uint32_t a = 0; a < platformCount; a++)
    {
        platformInfo(platforms, info, foo);
    }
    return 0;
}

和我有20个不同的函数重载 platformfo ();是否有一种方法来重载这个函数,唯一的变化是foo的数据类型,而不复制整个函数20次?

使用模板:

template<typename T>
int listPlatformInfo(..., T foo) // or T* ?
{
    ... 
    for (uint32_t a = 0; a < platformCount; a++)
    {
        platformInfo(platforms, info, foo);
    }
    return 0;
}

这就是为什么有泛型。参见模板函数:

    template<class T>
    void myGenericFunction(T parameter)
    {
        cout << parameter << " is of type "<< typeid(parameter).name() << endl;
    }
    int main()
    {
        myGenericFunction<int>(1);
        return 0;
    }