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]); }
相关文章推荐
- 在C++中怎样获得数组的大小?(原文标题:How Would You Get the Count of an Array in C++?)
- compile kernel error-- size of unnamed array is negative无名数组的大小为负
- How to find size of array in C/C++ without using sizeof ?
- How to get the size of file in C++ - 在C++中如何获取文件的大小
- C# 一个字符串是否在另外一个字符串数组里 Array.Exists 的用法 Array.IndexOf 用法
- c++传递数组大小的方式
- [jQuery] 如何根据名字来选取checkbox数组 -- How to get the array of checkbox via name
- [PHP] 计算文件夹大小 -- Determining the Size of a Directory’s Contents
- 字符串相互转字符数组 string byte 数组 array of byte
- C++中由数组大小引起的栈溢出
- C# 一个字符串是否在另外一个字符串数组里 Array.Exists 的用法 Array.IndexOf 用法
- C++实现数组大小运算符dimensionof()
- 对于一个SIZE大小的数组,元素是[0,SIZE-1]区间内的整数,判断其中是否有重复元素
- Given an array of size n, find all the possible sub set of the array of size k
- 一维数组的实现(Array, C++版)
- C++中使用 sizeof 函数取得数组大小
- The memory size of a C++ object instance.
- 【cookie的大小限制详解】Size of a request header field exceeds server limit .
- C++ 数组array与vector的比较
- 思路:C++数组大小的计算可以根据所占空间的大小。