Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of the parameter, templates, C++

There is the following simplified data structure:

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

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

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();
   ...
}
like image 517
CrocodileDundee Avatar asked Feb 20 '11 11:02

CrocodileDundee


People also ask

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How many types of templates are there in C?

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

What are non-type parameters for templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

What is the difference between typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.


2 Answers

Add a 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();
   ...
}
like image 154
Alexandre C. Avatar answered Oct 24 '22 16:10

Alexandre C.


You can use this:

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

Working example at http://www.ideone.com/t8KON .

Btw. if you use pointers as parameters, you have to use -> operator to call methods.

like image 24
Pawel Zubrycki Avatar answered Oct 24 '22 15:10

Pawel Zubrycki