Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在不知道对象类型的情况下使用多个对象的相同方法_C++_Class - Fatal编程技术网

C++ 在不知道对象类型的情况下使用多个对象的相同方法

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

我有一些类,命名为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(任意_类_类型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(); }