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();
...
}
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.
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.
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.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
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();
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With