已知大小typedefed数组的c ++函数模板专门化 [英] c++ function template specialization for known size typedefed array

查看:192
本文介绍了已知大小typedefed数组的c ++函数模板专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#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

很明显, sizeof func 指的是指针的大小,而不是 typedef 数组的大小,如 main()

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().

现在我不知道如何正确地做出让 func <

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?

非常感谢。

EDIT

实现专业化:

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

输出为:

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

我注意到 Pc A16_c

推荐答案

如果你想将数组的函数专门化,可以这样做:

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

这篇关于已知大小typedefed数组的c ++函数模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆