2017-07-24 67 views

回答

1

写一个模板函数很可能会做你想要什么:

template<typename any_class_type> 
int foo(any_class_type obj){ return process(obj.get_value); } 
0

您可以使用一个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

+0

只是一个旁注:虚拟多态性引入了大量的开销,只是模板没有。 – user0042

相关问题