C++ 设计新思维的修正和疑问(Compile Time Assertion)

1 view
Skip to first unread message

邱戈川

unread,
Mar 8, 2006, 1:35:42 AM3/8/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
对于Compile Time Assertion

书中有个例子如下:(名称有些不同)

template<bool>
class Check
{
public:
Check(...);
};

template <> class Check<false>{};

#define STATIC_CHECK(exp, msg) \
{\
class ERROR##msg {};\
(void)sizeof(Check<(exp)>(ERROR##msg()));\
}

使用VC7和最新的gcc都无法编译的过,难道是这个标准还没有支持?
所以尝试多次后改为:

template<bool>
class Check
{
public:
Check(...);
};

template <> class Check<false>{};

#define STATIC_CHECK(exp, msg) \
{\
class ERROR##msg {};\
ERROR##msg e;\
Check<(exp)> aCh(e);\
}

这里就不用使用sizeof了

candid Qiu

unread,
Mar 8, 2006, 2:24:54 AM3/8/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
注意:
这里是不能链接成功的,因为需要定义
Check(...);

Check(...){};
才可以!

邱戈川

unread,
Mar 8, 2006, 3:45:18 AM3/8/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
另外一种更简便的方式:
template<int x> struct static_assert_test{};

template <bool x> struct STATIC_ASSERTION_FAILURE;

template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 };
};

#define STATIC_ASSERT( B ) \
typedef static_assert_test < sizeof(STATIC_ASSERTION_FAILURE<( B )>)
> \
ERROR_ASSERT

小明

unread,
Mar 8, 2006, 10:16:26 PM3/8/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
Loki的实现:

namespace Loki
{
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
}

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

邱戈川

unread,
Mar 10, 2006, 1:27:19 AM3/10/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
在看template function的时候找到对于这个错误的解释:

因为编译器认为:
Check<(exp)>();
//这个不是构造一个类的实例,而是认为Check是个template
function,而且显式调用,其参数类型为exp。
所以编译不过。

Reply all
Reply to author
Forward
0 new messages