c++ - Printing out value of variable of unknown type? -


i'm trying write simple function template in c++ in printing out value of variable of unknown type. problem can't figure out how since variable either pointer or primitive type. primitive type, can print value out; pointers require de-referencing.

the following code gives me error:

#include <iostream> #include <type_traits>  using namespace std;  template<typename t> void foo(t somevar) {   if(std::is_fundamental<t>::value) {     cout << "it's primitive! \n" << somevar << endl;   } else {     cout << "it's pointer! \n" << *somevar << endl;   } }  int main(int argc, char **argv) {   int x = 5;   foo(x);    int *y = new int();   *y = 5;    foo(y);   delete y;    return 0; } 

the error when compile is:

test.cc: in function 'void foo(t) [with t = int]': test.cc:19:8:   instantiated here test.cc:13:5: error: invalid type argument of unary '*' (have 'int') 

it's complaining i'm trying de-reference primitive type first call foo(), that's why i'm using if-statement: check if it's primitive or not. how go implementing i'm trying do?

what need do, write 2 versions of templated function.

template<typename t> void foo(t somevar) {     cout << "assume it's primitive! \n" << somevar << endl; }  template<typename t> void foo(t* pvar) {     cout << "this pointer! \n" << *pvar << endl; } 

the compiler choose pointer version if works, because it's more specific. if type not (raw) pointer, default first version.

if need smart pointers dereferenced, can further overload function definition.

eg.

template<typename t> void foo(std::shared_ptr<t> pvar) {     cout << "this shared pointer! \n" << *pvar << endl; } 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -