+ 1

Why can I only run template function once?

I'm trying to make a custom print statement for ease of use, but I can only use the function once. Why is this? https://code.sololearn.com/chQG40vIrdhz/?ref=app

29th Jun 2020, 9:21 PM
Clueless Coder
Clueless Coder - avatar
3 odpowiedzi
+ 5
I wouldn't recommend giving templates default values like this. Here you call it like: print("hi ", "C++!"); C++ deduced that the type T = const char* Therefore T y = 0 and the other parameters are now pointer types pointing to 0. And then you try to print it. Yea, undefined behaviour. :) But even if you did check for y == nullptr and ditto for the other parameters, the function would complain again for other types. You could potentially default them to T y = T() to give them default types for every type, but that still wouldn't work for types that don't support default construction. Also do realize you can't mix types because you only use 1 template parameter. print( "hi", 1 ); would be illegal because T is deduced as const char* again. It can't be both that and an int. You could do template<typename T, typename U> ... etc to deal with each of them. That's why I gave you the variadic template function, it deals with that by itself. ( Lookup recursion as well if you don't understand it )
29th Jun 2020, 9:52 PM
Dennis
Dennis - avatar
+ 3
Not sure why...but declare your template like this: (default with empty strings). template <class T> void print(T x, T y="", T z="", T k="", T i=""){ cout << x << y << z << k << i << endl; }
29th Jun 2020, 9:42 PM
rodwynnejones
rodwynnejones - avatar
+ 2
rodwynnejones A bit late, but that does work weirdly. I'm gonna use that.
6th Jul 2020, 6:54 PM
Clueless Coder
Clueless Coder - avatar