user1285419
user1285419

Reputation: 2225

about using template trait in c++ to select data type

I am learning c++ template and want to apply the so-called template trait to select data type. I find some code online and make it work for my case

#include <iostream>

using namespace std;

template <bool T> struct TM;
template <> struct TM<true>  {typedef double MType;};
template <> struct TM<false> {typedef int MType;};

int main(int argc, char *argv[])
{
  TM<true>::MType x;
  TM<false>::MType y;

  cout << sizeof(x) << endl;
  cout << sizeof(y) << endl; 
  return 0;
}

It works pretty good. However, it seems that this only work for constant boolean instead of variable, so the following code doesn't work

#include <iostream>

using namespace std;

template <bool T> struct TM;
template <> struct TM<true>  {typedef double MType;};
template <> struct TM<false> {typedef int MType;};

int main(int argc, char *argv[])
{
  bool var=true;

  TM<var>::MType w;

  if (var) TM<true>::MType z;
  else TM<false>::MType z;

  cout << sizeof(w) << endl;
  cout << sizeof(z) << endl;
  return 0;
}

So is that true that template trait doesn't work the variable defined in run time? Thanks

Upvotes: 3

Views: 326

Answers (2)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

From cppreference :

Type traits defines an compile-time template-based interface to query or modify the properties of types.

In your case, TM<true> and TM<false are treated as two different types. TM<var>::MType will not let the compiler deduce the type. It will only be available at runtime, which is not correct. How the compiler can deduce which of the two types is it ?


From the standard :

20.9 Metaprogramming and type traits [meta]

This subclause describes components used by C++ programs, particularly in templates, to support the widest possible range of types, optimise template code usage, detect type related user errors, and perform type inference and transformation at compile time. [...]

Upvotes: 2

Sebastian Steger
Sebastian Steger

Reputation: 166

In C++, the compiler creates source code for all used template arguments from the templates. This is done during compilation. The created source code is then compiled as if it was regular source code.

Thus, in your case, TM<true> and TM<false> are treated as completely different types. If you write something like TM<var>::MType the compiler has no way of finding out which of the two types it is because the information will not be available before runtime.

Upvotes: 4

Related Questions