我有一些类,名为c1,c2,...都有一个共同名为get_value()的函数。 现在我想写一个这样的功能:使用几个对象的相同方法而不知道它们的类型
int foo(any_class_type obj){ return process(obj.get_value()); }
我该怎么做?
我有一些类,名为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); }
您可以使用一个function template
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(); }
或合并这些方法(当选择最佳匹配时)。
模板允许不相关的对象类型,并且倾向于生成比多态函数更高效的代码,但是仅用于标题,并且如果您使用没有拟合成员的参数调用它,也可能导致编译器错误消息繁琐getValue
。
只是一个旁注:虚拟多态性引入了大量的开销,只是模板没有。 – user0042
提供一个模板化的功能可能吗? – user0042
你能帮助我吗? –
我用一个例子写了一个答案。 – user0042