MCD里面给我们展现了许多高阶的C++ template技巧,大部分都是天才级别的人才能想出来的,与此同时,这些技巧也稍显前卫了,至少根据我对国内C++程序员的了解,能把STL玩的很好的已经少见了,并且里面的大部分技巧是在“挑战编译器”。
但是,我还是决定好好把这本书看完,一边看一边摘录书中以及loki库中的代码进行测试,权当开阔自己的视野。
一.compile assert编译器断言技巧
// 以下是书中的代码
template<bool> struct CompileTimeError;

template<> struct CompileTimeError<true>
{};

#define STATIC_CHECK(expr) \
(CompileTimeError< (expr) != 0>() )

template<bool> struct CompileTimeChecker


{
CompileTimeChecker(
);
};


template<> struct CompileTimeChecker<false>
{};

#define STATIC_CHECK_MSG(expr, msg) \

{\

class ERROR_##msg
{};\
(void)sizeof(CompileTimeChecker<(expr)> (ERROR_##msg()));\
}

// 以下是loki中的代码
namespace Loki


{
template<int> struct CompileTimeError;

template<> struct CompileTimeError<true>
{};
}

#define STATIC_CHECK_LOKI(expr, msg) \


{ Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg;}

int main(int argc, char *argv[])


{
// gcc不能编译,VC7编译通过
STATIC_CHECK(1);
// gcc,VC7都不能编译
//STATIC_CHECK_MSG(1, Error_Msg);
// gcc,VC7都能编译
STATIC_CHECK_LOKI(1, Error_Msg);

return 0;
}


这个东东的技巧在于:定义一个模版类,这个模版的模版参数是bool类型,对true的特化模版类进行了定义,而false的特化类没有定义,在使用的时候把需要断言的表达式作为模版参数来初始化这个模版类,如果为false,因为false的特化类没有定义,此时编译器会报错。
注意:这里的断言是在编译期进行的,与一般的运行时断言有区别。
未完待续....