Question

In our unit tests we have a few lines like:

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

And indeed if I uncomment this code it fails within LexicalCast at a static_assert:

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

As, in this case it would be unclear who owns the memory.

So my question is, using any advanced C++ features (I was thinking of SFINAE mainly but am not well versed in it) is it possible to check if something wouldn't compile due to a static_assert in the function called? I don't mind detection at runtime or compile time, and dont mind macros, etc, as these are tests.

EDIT: e.g. I want something like

ASSERT_DOESNT_COMPILE(::Utils::LexicalCast<const char*>(5));
Was it helpful?

Solution

The following example shows that SFINAE cannot help with 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;
}

When compiled with clang++ (3.4) and g++ (4.8.1), the static_assert fires although according to SFINAE it shouldn't. My conclusion is SAFIAE, i.e. Static_Assert Failure Is An Error.

OTHER TIPS

Perhaps too obvious, but ff you're only interested in this particular (static_assert) case, you can simply re#define it to something else:

#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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top