获取参数类型,模板,C ++ [英] Get type of the parameter, templates, C++

查看:159
本文介绍了获取参数类型,模板,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下简化的数据结构:

There is the following simplified data structure:

Object1.h

Object1.h

template <class T>
class Object1
{
  private:
     T a1;
     T a2;
  public:
     T getA1() {return a1;}
};

Object2.h

Object2.h

template <class T>
class Object2: public Object1 <T>
{
   private:
      T b1;
      T b2;
  public:
     T getB1() {return b1;}
}

有什么方法如何在下面的函数中获取对象的类型T:

Is there any way how to get type T of an object in the folowing function:

Functions.h

Functions.h

template <class Object>
void (Object *o1, Object *o2)
{
   T = o1.getA1();  //Is it possible to get T from object o1?
   ...
}

或者我们必须提供有关数据的附加信息两个对象的类型:

or we must give an additional information about data types of both objects:

template <class T, class Object>
void (Object *o1, Object *o2)
{
   T = o1.getA1();
   ...
}


推荐答案

添加typedef:

template <class T>
class Object1
{
  private:
     T a1;
     T a2;
  public:
     T getA1() {return a1;}
     typedef T type;
};

template <class Object>
void foo(Object *o1, Object *o2)
{
   typename Object::type x = o1.getA1();
   ...
}

这篇关于获取参数类型,模板,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆