开发者

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

开发者 https://www.devze.com 2023-01-23 17:25 出处:网络
I\'m wriging a wrapper for C++ of a function declared in this way: class MyClass { public: template <class T>

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 ca开发者_JS百科ll

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.


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.


As @Space_C0wb0y already pointed out, this isn't actually necessary. The template type is automatically inferred from the parameter.

However, C++0x does actually add what you asked for, in that it would let you write:

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

of course, in this case it's just a more complex way to solve a non-existent problem. But I thought I'd demonstrate it anyway, because it is so similar to the pseudocode you posted in the question.

0

精彩评论

暂无评论...
验证码 换一张
取 消