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

来源:互联网 发布:js正则表达式实例 编辑:程序博客网 时间:2024/05/18 02:12
////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 Endnamespace 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[N]> : 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]);}
0 0