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

时间:2012-07-18 10:42:59

标签: c++ polymorphism multiple-inheritance

在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派生的所有类

3 个答案:

答案 0 :(得分:4)

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

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

将使用以下类型

struct Foo
{
    void printA() const { std::cout << "FooA\n"; }
    void printB() const { std::cout << "FooB\n"; }
}

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();
} 

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

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();
}

N.B static_assertenable_ifis_base_of是C ++ 11的功能。如果您正在使用C ++ 03,则可以在各种Boost库中找到等效项。

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

托斯滕是对的。相反,如果在运行时看起来像“后期绑定”,你可以使用函数指针。您可以找到明确的示例here

相关问题