Template static member functions in C ++

I wrote a simple test program to try to learn how to use static member functions of a template in C ++. The code compiles, but does not work (it prints out some garbage). I guess I'm using the correct syntax. I read this or this and some other things, but still don’t know what I'm doing wrong. Code below:

#include <iostream> using namespace std; class Util { public: Util(); virtual ~Util(); template <typename T> static void printTab(T tab[]); }; template <typename T> void Util::printTab(T tab[]) { for (unsigned int i=0; i<sizeof(tab)/sizeof(tab[0]); i++) { cout << tab[0] << " "; } cout << endl; } int main() { float tabFloat[5] {1, 2, 3, 4, 5}; unsigned char tabChar[3] {1, 2, 3}; Util::printTab(tabFloat); Util::printTab(tabChar); return 0; } 

Any hints appreciated.

+4
source share
4 answers

You need to pass the size as another template argument:

 #include <iostream> using namespace std; class Util { public: Util(); virtual ~Util(); template <typename T,int N> static void printTab(T (&tab)[N]) { for (int i=0; i<N; i++) { cout << tab[i] << " "; } cout << endl; } }; int main() { float tabFloat[5] {1, 2, 3, 4, 5}; unsigned char tabChar[3] {1, 2, 3}; Util::printTab(tabFloat); Util::printTab(tabChar); } 
+5
source

sizeof(tab) is the size of T* , it will not return the size of the entire array. You must pass this in yourself as another argument to the function. See here for an explanation and another possible workaround: When a function has an array parameter of a certain size, why is it replaced with a pointer?

Note that the second printTab will not output readable characters. If you want to see something printed, try:

  unsigned char tabChar[3] {'1', '2', '3'}; 
+2
source

How to try, you need to send the size of the array when calling the function:

 #include <iostream> using namespace std; class Util { public: Util(); virtual ~Util(); template <typename T> static void printTab(T tab[], size_t sz); }; template <typename T> void Util::printTab(T tab[], size_t sz) { for (unsigned int i=0; i<sz; i++) { cout << tab[i] << " "; } cout << endl; } int main() { float tabFloat[5] {1, 2, 3, 4, 5}; unsigned char tabChar[3] {1, 2, 3}; Util::printTab(tabFloat, sizeof(tabFloat)/sizeof(float)); Util::printTab(tabChar, sizeof(tabChar)/sizeof(char)); return 0; } 
+1
source

I would pass the number of T elements as an argument to the function or use an STD container like Vector.

Your for loop just prints the first element tab[0] not tab[i]

In your initialization, tabFloat and tabChar are missing =

 float tabFloat[5] {1, 2, 3, 4, 5}; unsigned char tabChar[3] {1, 2, 3}; 

(I would also use 65, 66, 67 instead of 1,2,3 for readability in your testing).

 float tabFloat[5] = {1, 2, 3, 4, 5}; unsigned char tabChar[3] = { 65, 66, 67}; 
-1
source

Source: https://habr.com/ru/post/1383301/


All Articles