c++ function template specialization for known siz

2020-05-28 10:53发布

Please consider 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, I see this:

> 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

Clearly the sizeof printed inside func refers to the size of a pointer, and not the size of the typedef array, as given in main().

Now I wonder how to correctly do the trick for getting my func to specialize in such a way that it correctly knows about my typedef and its size.

Does anyone here can help me, please?

Really thanks.


EDIT

Implementing a 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;
}

The output is:

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

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

2条回答
够拽才男人
2楼-- · 2020-05-28 11:09

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

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;
}
查看更多
来,给爷笑一个
3楼-- · 2020-05-28 11:22

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

template <typename T, int N>
void f( T(&arg)[N] ) {
    cout << sizeof arg << endl;
}
查看更多
登录 后发表回答