【问题标题】:Get type of the parameter, templates, C++获取参数类型、模板、C++
【发布时间】:2011-06-30 17:03:14
【问题描述】:

有如下简化的数据结构:

Object1.h

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

Object2.h

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

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

函数.h

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

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

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

【问题讨论】:

  • 这在 C++0x 中是可能的。

标签: c++ templates types


【解决方案1】:

添加类型定义:

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

【讨论】:

  • 好像模板是“实例化的?”对于类型 T,你可以不写T x = o1...。我不明白为什么你需要 typedef,当 T 已经是一个类型时......
  • +1 表示 typedef,但恕我直言,它应该命名为 a1_type,而不仅仅是 type
【解决方案2】:

你可以用这个:

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

http://www.ideone.com/t8KON 的工作示例。

顺便说一句。如果使用指针作为参数,则必须使用-&gt; 运算符来调用方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2012-07-02
    • 1970-01-01
    • 2020-07-09
    • 2023-03-31
    • 2014-10-03
    相关资源
    最近更新 更多