Get the type of the template parameter from an object, C++
Here is my 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 to get the type T
from an object in the following function:
Functions.h
template <class Object>
void (Object *o1, Object *o2)
{
T = o1->getA1(); // Is it possible to get T from object o1?
// ...
}
Or must we give additional information about data types of both objects, like this:
开发者_开发技巧template <class T, class Object>
void (Object *o1, Object *o2)
{
T = o1->getA1();
// ...
}
Add a using
or typedef
statement, like this:
template <class T>
class Object1
{
private:
T a1;
T a2;
public:
T getA1() const {return a1;}
using type = T;
// or
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.
精彩评论