template to return its type


What is the best way to have a template return its type?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

when a template was instantiated the template type - for example T - was replaced by the concrete type and the instantiated function is not a template function anymore. hence you can do anything with the type as you could do with a concrete type as well.

//  return by value
template <class T>
T  f()
    return T(...);

// return by reference argument
template <class T>
void  g(T & t)
    t = T(...);

Open in new window

I assume you are looking for a mechanism similar to .NET's 'obj.GetType().ToString()' - in C++, that's RTTI or 'Run-Time Type Information' (https://msdn.microsoft.com/en-us/library/b2ay8610.aspx).  This feature however has to be enabled in your project's properties like

- Open the project's Property Pages dialog box.
- Click the C/C++ folder.
- Click the Language property page.
- Modify the Enable Run-Time Type Info property.

Then you can use RTTI like

#include <iostream>
using namespace std;

template<typename T> class foo {

  T t;

int main () {

  foo<char> f;

  cout << typeid(f).name() << endl;
  cout << typeid(f.t).name() << endl;

  return 0;

Open in new window


class foo<char>
a template type neither is a variant type nor a derived class type as you need to instantiate an explicit type when using a template. so if you use a template you know the type. that is much different to a base class pointer or base class reference where you might want to know the type of the derived class or to a variant type where different types share the same storage by means of a union.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.