Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how to get the type of a variable and use this as a template

I'm wriging a wrapper for C++ of a function declared in this way:

class MyClass
{
public:
  template <class T>
  T& as();
};

My wrapper needs to eliminate the explicit template because I don't want to call myClass.as<int>();

So I tried to implement a new function declared in this way:

class MyClass2 : public MyClass
{
public:
  template <class T>
  void get(T & val);
};

In this way I can call

int a;
myClass2.get(a);

Is there a way to implement this function, so the type is passed at runtime according to the parameter type? Something like:

template <class T>
void MyClass2::get(T & val)
{
  val = as< typeof(val) >();  /* Of course typeof does not exist */
}

Thank you very much for your help.

like image 296
yelo3 Avatar asked Dec 12 '22 18:12

yelo3


1 Answers

This does not make sense. Why not just write:

template <class T>
void MyClass2::get(T & val)
{
  val = as< T >();
}

Since the type is a template-parameter, you need no typeof.

like image 155
Björn Pollex Avatar answered Jan 19 '23 00:01

Björn Pollex