Can you find incompatible code?

In our unit tests, we have several lines, for example:

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

And indeed, if I uncomment this code, it fails in LexicalCast with static_assert:

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

Since in this case it would not be clear who owns the memory.

So, my question is to use any advanced features of C ++ (I was thinking about SFINAE mostly, but not very good at it), can I check if something is compiled due to static_assert in the called function? I do not mind detection at runtime or compile time, and also does not support macros, etc., since these are tests.

EDIT: e.g. I want something like

ASSERT_DOESNT_COMPILE(::Utils::LexicalCast<const char*>(5));
+4
source share
2

, 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 Failure Is Error.

+1

, , (static_assert), re # - :

#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;
}
-2

Source: https://habr.com/ru/post/1525630/


All Articles