c++ - Template equivalent of #var in macro -


in c++ macros can use #var literal string of argument passed:

#define print_size(type)                                                       \     (std::cout << sizeof(type) << " " << #type << std::endl) 

using macro, can write simple program give me lengths of specific types on machine:

print_size(bool); print_size(char); … 

this work use c++ templates instead. obtaining size easy following template function:

template <typename t> void print_size() {     std::cout << sizeof(t) << std::endl; } 

i can call function type , output size:

print_size<bool>(); print_size<char>(); … 

is there way literal "bool" anywhere such output nice 1 macros?

it can sortof done using rtti (runtime type inference) using typeid:

#include <iostream> #include <typeinfo>  template <typename t> void print_size() {         t a;         std::cout << typeid(a).name() << ": " << sizeof(t) << std::endl; }  int main(){      print_size<bool>();     print_size<char>();     print_size<long>();      return 0; } 

this outputs:

b: 1 c: 1 l: 8 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -