你能检测到无法编译的代码吗?

时间:2014-02-06 15:22:50

标签: c++ sfinae static-assert

在我们的单元测试中,我们有几行如下:

// Should not compile - manually checked
// auto val = ::Utils::LexicalCast<const char*>(5);

事实上,如果我取消注释这段代码,它会在一个static_assert中在LexicalCast中失败:

static_assert(!std::is_pointer<ToType>::value, "Cannot return pointers from a LexicalCast");

因为,在这种情况下,不清楚谁拥有记忆。

所以我的问题是,使用任何高级C ++功能(我主要考虑的是SFINAE,但我并不精通它)是否可以检查是否由于调用函数中的static_assert 而无法编译某些内容?我不介意在运行时或编译时检测,也不介意宏等,因为这些都是测试。

编辑:例如我想要像

这样的东西
ASSERT_DOESNT_COMPILE(::Utils::LexicalCast<const char*>(5));

2 个答案:

答案 0 :(得分:1)

以下示例显示SFINAE无法帮助static_assert

#include <type_traits>

// Fall back version that will always compile
template<class T>
void foo(T) {}

// Specific version using a static_assert that may or may not fire
template<class T>
void foo(T*) {
    static_assert(std::is_same<T, char>::value, "Boo");
}

int main(int argc, char** argv) {
    // This could call the fall back version, but the static_assert fires anyway
    foo((int*)0);
    return 0;
}

使用clang ++(3.4)和g ++(4.8.1)编译时,static_assert会触发,但根据SFINAE,它不应该触发。我的结论是SAFIAE,即Static_Assert失败是一个错误。

答案 1 :(得分:-2)

也许太明显了,但如果您只对这个特定的(static_assert)案例感兴趣,那么您可以简单地将其定义为其他内容:

#include <cassert>
#include <cstdio>
using namespace std;

#define static_assert(flag, msg) { assert(flag); }

int main()
{
    static_assert(false, "static_assert compile time");

    return 0;
}
相关问题