C ++ function template specialization for typed size array

Pay attention to the following code:

#include <iostream> #include <typeinfo> template< typename Type > void func( Type var ) { std::cout << __FUNCTION__ << ": var = " << var << " [" << typeid( var ).name( ) << "]." << std::endl; std::cout << "-> var is SCALAR. Size = " << sizeof( Type ) << std::endl; } #if 1 template< typename Type > void func( Type * var ) { std::cout << __FUNCTION__ << ": var = " << var << " [" << typeid( var ).name( ) << "]." << std::endl; std::cout << "-> var is ARRAY. Size = " << sizeof( Type * ) << std::endl; } #endif int main( ) { typedef char char16[ 16 ]; char16 c16 = "16 bytes chars."; std::cout << "Size of char16 = " << sizeof( char16 ) << std::endl; func( c16 ); return 0; } 

If I compile it and run it, I see the following:

 > g++ -Wall -g3 spec_f_pointer.cpp -o spec_f_pointer > ./spec_f_pointer Size of char16 = 16 func: var = 16 bytes chars. [Pc]. -> var is ARRAY. Size = 8 

Obviously, the sizeof printed inside func refers to the size of the pointer, not the size of the typedef array, as indicated in main() .

Now I'm wondering how to do the trick correctly so that my func specializes so that it knows correctly about my typedef and its size.

Can anyone help me please?

Thanks actually.


EDIT

Implementation of specialization as:

 template< typename Type > void func( Type * const &var ) { std::cout << __FUNCTION__ << ": var = " << var << " [" << typeid( var ).name( ) << "]." << std::endl; std::cout << "-> var is ARRAY. Size = " << sizeof( Type * ) << std::endl; } 

Output:

 Size of char16 = 16 func: var = 16 bytes chars. [A16_c]. -> var is SCALAR. Size = 16 

I noticed a type change from Pc to A16_c . Does it help?

+7
source share
2 answers

If you want to specialize your function for arrays, do the following:

 template<typename T, int N> void func(T(&var)[N]) { typedef T Type[N]; std::cout << __FUNCTION__ << " [" << typeid( var ).name( ) << "]." << std::endl; std::cout << "-> var is ARRAY. Size = " << sizeof( Type ) << std::endl; std::cout << "Number of elements: " << N << std::endl; std::cout << "Size of each element: " << sizeof(T) << std::endl; } 
+12
source

When rvalue is used as expressions, arrays break up into pointers to the first element. The function you defined takes a pointer and does what is expected. If you want to save the array as an array, you need to pass it by reference, and since the number of elements is part of the type that you probably want to use as another template argument:

 template <typename T, int N> void f( T(&arg)[N] ) { cout << sizeof arg << endl; } 
+1
source

All Articles