是否可以为函数参数指定多个类型

Is it possible to specify multiple types for a function parameter?

本文关键字:类型 参数 函数 是否      更新时间:2023-10-16
是否可以

C++定义一个函数参数为多个类型?

#include <iostream>
using namespace std;
class A {
public:
   void  PrintA() { cout << "A" << endl;}
};
class B {
public:
   void  PrintB() { cout << "B" << endl;}
};
class C: public A, public B {
public:
   C(){;}
};
class D: public A, public B {
public:
   D(){;}
};
///
void __printall__(A*a, B*b){
   a->PrintA();
   b->PrintB();
}
#define printall(a) __printall__(a,a)
///
int main(int argc, char *argv[]){
   C c;
   D d;
   printall(&c);
   printall(&d);
}

我想用不使用宏的东西更改注释之间的代码。我不会强制强制转换指针,因为我想保持类型安全。我什至不会在 C/D 和 A/B 之间引入另一个类,因为实际上我的类层次结构比代码中显示的要复杂一些,并且不希望重新设置从 A 或 B 派生的所有类的基数。

@Torsten建议的那样,可能的解决方案是使用函数模板,以便可以传递任何类型的参数。但是,一个简单的模板将适用于提供适当成员的任何类型(在本例中为 printAprintB (,因此以下函数模板

template <typename T>
void printAll(T const & t)
{
    t.printA();
    t.printB();
}

将使用以下类型

struct Foo
{
    void printA() const { std::cout << "FooAn"; }
    void printB() const { std::cout << "FooBn"; }
}
printAll(Foo());

即使Foo不是从AB派生的。这可能是可取的,但是如果您真的想强制执行参数必须是AB的事实,则可以在函数中使用静态断言来检查:

#include <type_traits>
template <typename T>
void printAll(T const & t)
{
    static_assert(std::is_base_of<A, T>::value && std::is_base_of<B, T>::value,
                  "T must be derived from A and B");
    t.printA();
    t.printB();
} 

另一种解决方案是仅当模板参数确实是 AB 的派生类时,才使用 std::enable_if 来定义函数模板:

template<
    typename T ,
    typename = typename std::enable_if<
        std::is_base_of<A, T>::value &&
        std::is_base_of<B, T>::value
    >::type
>
void printAll(T const & t)
{
    t.printA();
    t.printB();
}

注意static_assertenable_ifis_base_of是C++11的特征。如果您使用的是 C++03,则可以在各种 Boost 库中找到等效项。

模板版本将只选择传递给函数的类型:

template < class T >
void printall( T* t )
{
   t->printA();
   t->printB();
}

Torsten是对的。相反,如果在运行时看起来像"后期绑定",则可以使用函数指针。你可以在这里找到一个明显的例子。