编译时间sizeof_array而不使用宏 [英] Compile time sizeof_array without using a macro

查看:159
本文介绍了编译时间sizeof_array而不使用宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是在过去几天里困扰我的东西,我不认为这是可能解决,但我以前见过模板魔术。

This is just something that has bothered me for the last couple of days, I don't think it's possible to solve but I've seen template magic before.

这里:

要获取标准C ++数组中的元素数量,我可以使用宏(1)或类型安全的内联函数(2):

To get the number of elements in a standard C++ array I could use either a macro (1), or a typesafe inline function (2):

(1)

#define sizeof_array(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0]))



< (2)

template <typename T>
size_t sizeof_array(const T& ARRAY){
    return (sizeof(ARRAY)/sizeof(ARRAY[0]));
}



如你所见,第一个有一个问题:目前我认为一个问题),另一个有一个问题,即不能在编译时获取数组的大小;即我不能写:

As you can see, the first one has the problem of being a macro (for the moment I consider that a problem) and the other one has the problem of not being able to get the size of an array at compile time; ie I can't write:

enum ENUM{N=sizeof_array(ARRAY)};

BOOST_STATIC_ASSERT(sizeof_array(ARRAY)==10);// Assuming the size 10..

有人知道这是否可以解决?

Does anyone know if this can be solved?

推荐答案

请尝试从此处

template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define mycountof( array ) (sizeof( _ArraySizeHelper( array ) ))

int testarray[10];
enum { testsize = mycountof(testarray) };

void test() {
    printf("The array count is: %d\n", testsize);
}

它应该打印出:数组计数为:10

It should print out: "The array count is: 10"

这篇关于编译时间sizeof_array而不使用宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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