C++について、知っていそうで知らないこと、素朴な疑問など。(新着順)
定数の定義をソースコード上で行う場合、定数の定義と値の定義を同時に行いたい場合があります。
通常はこのように書きます。
enum EnumHoge { hoge, fuga, piyo }; struct HogeHoge { EnumHoge id; float value; const char* name; } const table[] = { { hoge, 1.0f, "hoge" }, { fuga, 2.0f, "fuga" }, { piyo, 3.0f, "piyo" }, };
enumの定義と構造体の定義が冗長で、名前の文字列の定義も冗長です。
しかし、魂を悪魔(#define)に売り渡せば、一発で記述できます。
// ここで定数を定義する(冗長でない単一の記載で済ませる) #define LIST \ DEF(hoge, 1.0f), \ DEF(fuga, 2.0f), \ DEF(piyo, 3.0f) // enumの生成 #undef DEF #define DEF(a, b) a enum EnumHoge { LIST }; // 構造体の生成 #undef DEF #define DEF(a, b) {a, b, #a} struct HogeHoge { EnumHoge id; float value; const char* name; } const table[] = { LIST };
使用例
#include <stdio.h> int main(int ac, char*av []) { for (size_t n = 0; n < sizeof(table)/sizeof(HogeHoge); ++n) { printf("table[%d] = id:%d value:%f name='%s'\n", n, table[n].id, table[n].value, table[n].name); } }
結果
table[0] = id:0 value:1.000000 name='hoge' table[1] = id:1 value:2.000000 name='gufa' table[2] = id:2 value:3.000000 name='piyo'
ideone: http://ideone.com/HEIsAa#view_edit_box
// decltypeを使ってコンテナに要素を追加する // push_back()を持っている場合 template <typename CT, typename VT> inline auto push_to_container(CT& container, VT&& val, int=0) -> decltype(container.push_back(val)) { return container.push_back(val); } // push()がある場合 template <typename CT, typename VT> inline auto push_to_container(CT& container, VT&& val) -> decltype(container.push(val)) { return container.push(val); }
使用例
std::vector<int> hoge; std::priority_queue<int> fuga; ... push_to_container(hoge, 1); // hoge.push_back(1)が呼ばれる push_to_container(fuga, 1); // fuga.push(1)が呼ばれる
参考にしたページ
VC++では、イテレーターの範囲チェックが行われており、安全な反面、若干遅いです。
以下の定義を行うことで、範囲チェックを無効にできます。(C++ポケットリファレンスより引用)
#define _SECURE_SCL 0
ちなみに、以下の設定で範囲チェックが有効になります。
#define _SECURE_SCL_1 #define _HAS_ITERATOR_DEBUGGING 1
boost::mplのvectorやmapをfor_eachするサンプル。 mapのkeyだけ回すmap_keysのようなフィルタの例も作ってみました。
#include <iostream> #include <vector> #include <string> #include <typeinfo> #include <boost/mpl/list.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/key_type.hpp> using namespace boost; using namespace std; struct Disp { template <class Type> void operator()(const Type&) const { cout << typeid(Type).name() << endl; } template <typename K, typename V> void operator()(const mpl::pair<K,V>&) const { cout << typeid(K).name() << "," << typeid(V).name() << endl; } } disp; int main() { typedef mpl::list<int, std::string, char, std::vector<int> > tl; typedef mpl::map<mpl::pair<int,char>, mpl::pair<int,int>, mpl::pair<char, char> > t2; cout << "mpl list test" << endl; mpl::for_each<tl>(disp); cout << "mpl map test" << endl; mpl::for_each<t2>(disp); cout << "mpl map key_type test" << endl; mpl::for_each<t2, mpl::lambda<mpl::key_type<t2, mpl::_1> > >(disp); cout << "finish" << endl; return 0; }
cpp_akiraさんのページにあったサンプルにmapを足してみました。