是否可以为函数参数指定多个类型
Is it possible to specify multiple types for a function parameter?
是否可以
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建议的那样,可能的解决方案是使用函数模板,以便可以传递任何类型的参数。但是,一个简单的模板将适用于提供适当成员的任何类型(在本例中为 printA
和 printB
(,因此以下函数模板
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
不是从A
或B
派生的。这可能是可取的,但是如果您真的想强制执行参数必须是A
和B
的事实,则可以在函数中使用静态断言来检查:
#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();
}
另一种解决方案是仅当模板参数确实是 A
和 B
的派生类时,才使用 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_assert
、enable_if
和is_base_of
是C++11的特征。如果您使用的是 C++03,则可以在各种 Boost 库中找到等效项。
模板版本将只选择传递给函数的类型:
template < class T >
void printall( T* t )
{
t->printA();
t->printB();
}
Torsten是对的。相反,如果在运行时看起来像"后期绑定",则可以使用函数指针。你可以在这里找到一个明显的例子。
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法