c ++:gcc是否提供扩展的宏/函数,如“countof”数组的大小? [英] c++: Does gcc provide extended macro/function like "countof" the size of an array?

查看:398
本文介绍了c ++:gcc是否提供扩展的宏/函数,如“countof”数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VC提供了一个名为_countof的stdlib.h内的宏,它将在编译时计算一个数组元素的个数。



我的问题是gcc提供了一个类似的工具?
Thanks。

解决方案

在C ++ 17中, std :: size 函数模板将返回数组或容器的大小。



可能实现,因此您可以编写自己的代码,直到C ++ 17变得可用为止:

  template< class T,std :: size_t N> 
constexpr std :: size_t size(const T(& array)[N])noexcept
{
return N;
}

这适用于任何符合C ++ 11编译器,所以它是比编译器特定的扩展更便于携带。


VC provides a macro called "_countof" inside "stdlib.h", will calculates in compile time, the number of an array's elements.

My question is does gcc provide a similar utility? Thanks.

解决方案

In C++17, the std::size function template will return the size of an array or container.

A possible implementation is given, so you can write your own until C++17 becomes available:

template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
    return N;
}

This will work on any conforming C++11 compiler, so it is a lot more portable than compiler-specific extensions.

这篇关于c ++:gcc是否提供扩展的宏/函数,如“countof”数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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