modern c++ design 读后有感
一、静态检查
1、通过编译器数组长度不能为0设计
// 编译器检查:编译期无法分配0元素数组
#define STATIC_CHECK(expr) { char unnamed[(expr) ? 1 : 0]; }
2、通过模板特性,不使用相关代码时,代码是不会实例化的
template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECKT(expr) \
(CompileTimeError<(expr) != 0>())
表达式expr为false时,会提示没有实例化而报错
二、无名域名
无名域名使用时,只能在本文件使用,例如:
namespace
{
。。。。。。
}
三、Local class
Local classes are an interesting and little-known feature of C++. You can define classes right inside functions, as follows:
void Fun()
{
class Local
{
... member variables ...
... member function definitions ...
};
... code using Local ...
}
There are some limitations—local classes cannot define static member variables and cannot access nonstatic local variables. What makes local classes truly interesting is that you can use them in template functions. Local classes defined inside template functions can use the template parameters of the enclosing function
class Interface
{
public:
virtual void Fun() = 0;
};
template <class T, class P>
Interface* MakeAdapter(const T& obj, const P& arg)