我想编写一个 C++ 库,默认情况下它不是仅标头,但可以用作定义NOLIB
宏的仅标头库。
我见过两种方法:
- 内联定义
foo.h
#if !defined(FOO_H)
#define FOO_H
#if defined(NOLIB)
# define MYINLINE inline
#else
# define MYINLINE
#endif
class foo
{
// ...
};
#if defined(NOLIB)
# include "foo.cc"
#endif
#endif // include guard
foo.cc
#if !defined(NOLIB)
# include "foo.h"
#endif
MYINLINE void foo::something() { ... }
- “人工”模板
foo.h
#if !defined(FOO_H)
#define FOO_H
#if defined(NOLIB)
# define MYTEMPLATE template<bool DUMMY>
# define MYFOO foo_impl
# define MYFOO_T foo_impl<DUMMY>
#else
# define MYTEMPLATE
# define MYFOO foo
# define MYFOO_T foo
#endif
MYTEMPLATE
class MYFOO
{
// ...
};
#if defined(NOLIB)
using foo = foo_impl<true>;
# include "foo.cc"
#endif
#endif // include guard
foo.cc
#if !defined(NOLIB)
# include "foo.h"
#endif
MYTEMPLATE
void MYFOO_T::something() { ... }
这些方法的优缺点是什么?有更好的选择吗?