2015-03-19 61 views
3

我需要知道在指定noexcept说明符时是否定义了NDEBUG。我沿着这constexpr功能的思路思考:is_defined constexpr函数

constexpr inline bool is_defined() noexcept 
{ 
    return false; 
} 

constexpr inline bool is_defined(int) noexcept 
{ 
    return true; 
} 

然后使用它像:

void f() noexcept(is_defined(NDEBUG)) 
{ 
    // blah, blah 
} 

是否标准库或已在各种语言的提供便利,这样我就不会重新发明轮子?

回答

2

如果您只对NDEBUG感兴趣,这相当于测试assert()是否评估它的参数。在这种情况下,你可以使用:

void f() noexcept(noexcept(assert((throw true,true)))) 
{ 
    // ... 
} 

这是当然,不一定是改善:)

+0

非常有趣的技巧。 – user1095108 2015-03-19 17:39:49

5

只需使用#ifdef

#ifdef NDEBUG 
using is_ndebug = std::true_type; 
#else 
using is_ndebug = std::false_type; 
#endif 

void f() noexcept(is_ndebug{}) { 
    // blah, blah 
} 

或其它类似的方式无数:甲constexpr函数返回boolstd::true_type(有条件地)。两种类型之一的一个变量static。一个特征类,需要一个列举各种#define令牌等价物(eNDEBUG等)的enum,它可以专用于它支持的每个此类标记,并在没有此类支持时生成错误。使用typedef而不是using(如果你的编译器有使用的片状支持,我在看你MSVC2013)。我确定可以有其他人。

+0

有无数的方法,但并非所有的工作,因为编译器的bug。它是gcc:错误'noexcept()'具有不同的异常说明符' – user1095108 2015-03-19 13:58:30