C++ 在不知道对象类型的情况下使用多个对象的相同方法
我有一些类,命名为c1,c2。。。它们都有一个共同的函数,名为get_value()。 现在我想写一个这样的函数:C++ 在不知道对象类型的情况下使用多个对象的相同方法,c++,class,C++,Class,我有一些类,命名为c1,c2。。。它们都有一个共同的函数,名为get_value()。 现在我想写一个这样的函数: int foo(any_class_type obj){ return process(obj.get_value() ); } 我该怎么做 编写模板化函数可能会满足您的需要: template<typename any_class_type> int foo(any_class_type obj){ return process(obj.get_value); }
int foo(any_class_type obj){ return process(obj.get_value() ); }
我该怎么做 编写模板化函数可能会满足您的需要:
template<typename any_class_type>
int foo(any_class_type obj){ return process(obj.get_value); }
模板
int foo(任意_类_类型obj){返回进程(obj.get_值);}
您可以使用
或者为(某些)类型显式重载函数
或者结合这些方法(当选择最佳匹配时)
模板允许不相关的对象类型,并倾向于生成比多态函数更高效的代码,但是,如果您使用一个没有合适成员的参数调用它,那么它可能只包含头,并且可能会导致繁琐的编译器错误消息。
getValue
可能会提供一个模板函数吗?您能帮我更多忙吗?我用一个示例写了一个答案。c1
和c2
是否有可能继承自一个公共基类?@user4581301他们真的需要一个公共基类吗?只是一个旁注:虚拟多态性引入了巨大的开销,而模板化却没有。
template<typename T>
int foo(T const&obj)
{
return obj.getValue();
}
struct C
{
virtual int getValue() const = 0;
};
struct C1 : C
{
int getValue() const override;
};
struct C2 : C
{
int getValue() const override;
};
int foo(C const&obj)
{
return obj.getValue();
}
int foo(C1 const&obj) { return obj.getValue(); }
int foo(C2 const&obj) { return obj.getValue(); }