melt日記

.NETすらまともに扱えないへたれのページ

ホーム 連絡をする 同期する ( RSS 2.0 ) Login
投稿数  111  : 記事  3  : コメント  8241  : トラックバック  41

ニュース

わんくま同盟

わんくま同盟

C# と VB.NET の質問掲示板

iKnow!


Dictation



書庫

_countof は、固定長配列の要素数を取得するためのマクロです。

古く C 言語時代から使用されている要素数を調べるためのマクロは、

#define ELEM_NUM(a) (sizeof(a) / sizeof((a)[0]))

こんな風になっているのですが、これだとポインタの要素数も取れてしまいます。

int ar[5];
int* par = ar;
int size = ELEM_NUM(par); // 間違い

型安全で静的に要素数を取得するには _countof マクロを使用します。

int ar[5];
int* par = ar;
_countof(par); // コンパイルエラー

今日はこの _countof マクロの実装について調べてみようと思います。


_countof の定義を見てみると、こんな風になっています。

template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) sizeof(*__countof_helper(_Array))

……これをパッと見て理解できたそこのあなた。あなたは間違いなく変態です。


まあそれはおいといて、とりあえず分かりづらいのでいらない値を取り除いて整形しておきます。

template <typename Type, size_t Size>
char (*__countof_helper(Type (&ar)[Size]))[Size];
#define _countof(ar) sizeof(*__countof_helper(ar))

で、まずはこのマクロから離れて、ウォーミングアップとして固定長配列に慣れるとこから始めてみます。

まず小手調べ。

void func(Hoge (&ar)[10]);

こうやって書くと、ar は固定長配列への参照(Hoge[10]& 型)になります。

Hoge[10]& 型以外は受け付けません。例えば、

Hoge ar[10];
func(ar); // OK
Hoge* par = ar;
func(par); // NG
Hoge ar2[5];
func(ar2); // NG

こんな風にポインタや要素数の違う配列を渡すと、型の不整合でコンパイル時にエラーになってくれます。


次に、固定長配列へのポインタを返す関数の宣言を考えてみます。

typedef Hoge (*HogeArrayPtr)[10];
HogeArrayPtr func();

こうなります。

Hoge[10]* 型を返す関数 func の出来上がりです。

これを、typedef を使わずに書いてみるとどうなるか分かりますか?

Hoge (*func())[10];

こうなります。何か難しい感じがしますが、これは↑の typedef を使った構文と全く同じ意味です。


で、これを踏まえた上で __countof_helper を読んでみると、先ほどの固定長配列を返す関数の構文と同じであることに気が付きます。

char (*__countof_helper(Type (&ar)[Size]))[Size];

Type (&ar)[Size] というのは、Type[Size] への参照を取る ar の宣言を意味していて、char (*func(...))[Size] というのは、char[Size] へのポインタを取る func() の宣言を意味しています。


つまり、__countof_helper というのは Type[Size]& 型の引数を取って char[Size]* 型を返す関数(の宣言)ということです。


これを typedef してみると、

typedef char (*CharArrayPtr)[Size];
typedef Type (&TypeArrayRef)[Size];
CharArrayPtr __countof_helper(TypeArrayRef ar);

こんな感じになります(本当は Size は template 引数なのでこうするのは不可能ですが)。


ここまでくれば後は簡単で、__countof_helper は char[Size]* 型を返すので、

*__countof_helper(ar);

とすれば char[Size] 型が返され、

sizeof(*__countof_helper(ar));

とすれば char[Size] の大きさ、つまり sizeof(char) * Size の大きさがコンパイル時に求められます。

これが _countof の定義です。



自分が _countof の定義を見て学んだ一番のことは、「関数ポインタと固定長配列を typedef せずに関数の戻り値として使うのはやめておけ」ということでした。

みなさんもこのエントリで何か見つけて頂ければと思います。

投稿日時 : 2008年3月8日 0:10

コメント

# re: [C++]_countof マクロ 2008/03/08 13:14 アキラ
C++0xのconstexprがはやくほしいなー、と思いました
コンパイル時に実行される関数を作れたほうが手っ取り早いw

template <class T, size_t Size>
constexpr size_t count_of(const T(&ar)[Size])
{
 return Size;
}

int ar[3];
int arr[count_of(ar)]; // arの要素数で新たな配列作成

さよなら変態テクニックw

# re: [C++]_countof マクロ 2008/03/08 22:30 シャノン
昔挑戦しましたよ。
配列の要素数までテンプレートに推測させるのが鬼だと思いました。

# re: [C++]コードチェック 2008/05/29 1:24 melt日記
re: [C++]コードチェック

# fHQNWKFjyOGBkzfyWQm 2014/08/28 9:47 http://crorkz.com/
rOaDVA I savor, result in I discovered exactly what I was taking a look for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

# re: [C++]_countof マクロ 2015/08/27 11:31 AAA
素晴らしい!

# re: 無意味なコメント(前回ソースゴミのエントリーの延長線) 2017/07/24 11:48 zzzzz
http://www.nbajerseys.us.org/
http://www.pandorajewelryoutlets.in.net/
http://www.uggboots-forwomen.in.net/
http://www.nikeshoes2017.us.com/
http://www.michaelkors-handbags.org.uk/
http://www.nikeshoesoutlet.us.org/
http://indianapoliscolts.jerseyscheap.us.com/
http://www.louisvuitton-sacpascher.fr/
http://www.dolceandgabbana.in.net/
http://www.cheapray-banssunglasses.us.com/
http://chicagobears.jerseyscheap.us.com/
http://www.coachoutlet-storeonline.com.co/
http://www.fitflopssale-clearances.us.com/
http://www.uggsforwomen.eu.com/
http://www.kate-spadehandbags.us.com/
http://www.true-religionoutlets.us.com/
http://www.eccoshoesoutlet.us/
http://www.nikehuarache2017.in.net/
http://www.montblancpensoutlet.com.co/
http://www.nikestores.org.uk/
http://www.chaussurelouboutinpas-cher.fr/
http://atlantafalcons.jerseyscheap.us.com/
http://www.christianlouboutinoutlets.us/
http://www.nhljerseyswholesaler.us.com/
http://www.fitflopsclearancesale.us.com/
http://www.polo-outlets.us.com/
http://newenglandpatriots.jerseyscheap.us.com/
http://www.nikeoutlet-stores.us.com/
http://www.nikeblazerlow.fr/
http://www.nikefactorystore.us.com/
http://www.prada-shoes.us.com/
http://www.replicawatchesforsale.us.com/
http://www.redvalentino.in.net/
http://www.ugg-slippers.de.com/
http://www.uggs-forwomen.de.com/
http://www.conversetrainer.org.uk/
http://www.uggs-onsale.eu.com/
http://sanfrancisco49ers.jerseyscheap.us.com/
http://www.cheapjordanshoes.in.net/
http://neworleanssaints.jerseyscheap.us.com/
http://www.truereligionjeansoutletonline.us.com/
http://www.ugg-slippers.eu.com/
http://www.michaelkors-handbagswholesale.in.net/
http://www.new-balanceshoes.in.net/
http://www.michaelkorshandbagswholesale.in.net/
http://www.ralph-laurenoutlets.us.com/
http://miamidolphins.jerseyscheap.us.com/
http://www.coachoutletstore-online.eu.com/
http://www.raybanssunglasses.net.co/
http://www.oakleysunglassesoutlete.us.com/


# yezi20160620@163.com 2017/09/28 10:17 wwwww
http://www.jordan6.us.com
http://www.adidasnmdrunner.us.com
http://www.adidastubular.us.com
http://www.hoganoutlet.cc
http://www.outletlongchamp.us.com
http://www.adidasultra.us.com
http://www.rosherun.us.com
http://www.longchampbags.us.org
http://www.adidassuperstar.org.uk
http://www.airjordan.us.com
http://www.adidasyeezyshoes.us.org
http://www.adidastubular.co.uk
http://www.goldengoose-snearkers.com
http://www.airhuarache.uk
http://www.nikeairmax2018.us.com
http://www.vancleefarpels.us.com
http://www.pradasunglasses.us.org
http://www.kyrie3.us.com
http://www.nike-huarache.com
http://www.cheapretro-jordans.com
WWWW

# re: [C++]_countof マクロ 2017/11/28 12:06 cc
http://www.yeezy-shoes.org.uk
http://www.nikehuaracheshoes.us.com
http://www.cartierbracelet.us
http://www.michaelkors-outletonlines.us.com
http://www.vibramfivefingers.us.com
http://www.kobebasketballshoes.net
http://www.jordan11retro.us.com
http://www.ultraboost.us.com
http://www.michaelkors-factoryoutlet.com.co
http://www.thelightupshoes.us.com
http://www.airmax90.us.org
http://www.longchamp-bags.us.org
http://www.jordan6.us.com
http://www.cheap--jordans.us.com
http://www.lebron13.us.com
http://www.jordan-retro.us.com


# re: [C++]_countof ??? 2021/08/07 4:13 hydroxy chloriquine
side effects of chloroquine https://chloroquineorigin.com/# hydroxychloriquine

# stromectol covid http://stromectolabc.com/
stromectol generic 2022/02/07 17:14 Busjdhj
stromectol covid http://stromectolabc.com/
stromectol generic

# 100mg doxycycline https://doxycyline1st.com/
doxycycline online 2022/02/25 22:00 Doxycycline
100mg doxycycline https://doxycyline1st.com/
doxycycline online

# doxycycline hyc https://doxycyline1st.com/
doxycycline mono 2022/02/26 9:14 Doxycycline
doxycycline hyc https://doxycyline1st.com/
doxycycline mono

# paxlovid availability https://paxlovid.best/
where can i get paxlovid 2022/09/07 22:29 Paxlovid
paxlovid availability https://paxlovid.best/
where can i get paxlovid

# pills erectile dysfunction https://erectiledysfunctionpills.shop/ 2022/10/14 16:21 Erectile
pills erectile dysfunction https://erectiledysfunctionpills.shop/

# erectile dysfunction medications https://ed-pills.site/
online ed medications 2022/11/17 15:50 EdPills
erectile dysfunction medications https://ed-pills.site/
online ed medications

# prednisone cost canada https://prednisonepills.site/
cost of prednisone 5mg tablets 2022/11/28 16:32 Prednisone
prednisone cost canada https://prednisonepills.site/
cost of prednisone 5mg tablets

# how to cure ed https://edpills.science/
ed medications 2023/01/07 8:19 EdPills
how to cure ed https://edpills.science/
ed medications

# buy cytotec over the counter - https://cytotecsale.pro/# 2023/04/28 13:00 Cytotec
buy cytotec over the counter - https://cytotecsale.pro/#

# nausea medication over the counter https://overthecounter.pro/# 2023/05/08 12:46 OtcJikoliuj
nausea medication over the counter https://overthecounter.pro/#

# treatment for ed https://edpill.pro/# - pills for ed 2023/06/27 5:16 EdPills
treatment for ed https://edpill.pro/# - pills for ed

# best dating websites online 2023/08/09 16:09 WayneGurry
online dting: http://datingtopreview.com/# - dating service

# farmacia online piГ№ conveniente 2023/09/24 21:58 Archieonelf
https://pharmacieenligne.icu/# Pharmacies en ligne certifiГ©es

# migliori farmacie online 2023 2023/09/28 5:44 Rickeyrof
acheter sildenafil 100mg sans ordonnance

# acquistare farmaci senza ricetta 2023/09/30 5:46 Rickeyrof
acheter sildenafil 100mg sans ordonnance

# doxycycline south africa 2023/10/09 13:29 GaylordPah
Their international supply chain ensures no medication shortages. https://doxycyclineotc.store/# doxycycline 200 mg tablets

# paxlovid covid 2023/10/23 21:18 LarryNef
http://valtrex.auction/# valtrex mexico

# farmacie on line spedizione gratuita https://farmaciait.pro/ farmaci senza ricetta elenco 2023/12/04 3:38 Farmacia
farmacie on line spedizione gratuita https://farmaciait.pro/ farmaci senza ricetta elenco

# average cost of prednisone https://prednisone.bid/ prednisone cream rx 2023/12/27 2:26 Prednisone
average cost of prednisone https://prednisone.bid/ prednisone cream rx

# ï»¿cytotec pills online https://cytotec.club/ cytotec online 2024/04/28 2:06 Cytotec
cytotec pills online https://cytotec.club/ cytotec online

Post Feedback

タイトル
名前
Url:
コメント