您的位置:首页 > 编程语言 > C语言/C++

C++中数组的大小(SizeOfArray)

2017-01-20 10:59 393 查看
////Loki Start
////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2001 by Andrei Alexandrescu
// This code accompanies the book:
// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design 
//     Patterns Applied". Copyright (c) 2001. Addison-Wesley.
// Permission to use, copy, modify, distribute and sell this software for any 
//     purpose is hereby granted without fee, provided that the above copyright 
//     notice appear in all copies and that both that copyright notice and this 
//     permission notice appear in supporting documentation.
// The author or Addison-Wesley Longman make no representations about the 
//     suitability of this software for any purpose. It is provided "as is" 
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
/*
* 取自Loki, 静态断言
*  比如用以下语句来确认size_t类型可以准确存储一个指针
*   STATIC_ASSERT(sizeof(size_t) == sizeof(void*), SIZE_T_LENGTH_NOT_SUITABLE);
*/
#define STATIC_ASSERT(expr, msg) \
{ CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
////Loki End

namespace InnerTypeTraits
{
    // bool_type, 用于返回一个常量
    template<bool b_>
    struct bool_type{
        static const bool value = b_;
    };
    template<bool b_>
    const bool bool_type<b_>::value;

    // is_array<T>, 判断T是否是数组
    template<typename T>
    struct is_array : bool_type<false>{
    };
    template<typename T>
    struct is_array<T[]>: bool_type<true>{
    };
    template<typename T, unsigned int N>
    struct is_array<T
> : bool_type<true>{
    };
}

// START SizeOfArray 定义
// 作用:判定数组元素的个数
// 优点:如果误传普通指针,则编译报错
template<typename T>
size_t SizeOfArray(T& t)
{
    STATIC_ASSERT(InnerSafePtr::InnerTypeTraits::is_array<T>::value, typeNotArray);
    return sizeof(t)/sizeof(t[0]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息