Dominic Birmingham
Dominic Birmingham

Reputation: 325

How can I force a compile error in C++?

I would like to create a compile-time error in my C++ code with a custom error message. I want to do this for a couple of reasons:

I'm sure there is a trick to doing this but I cant find a resource explaining the method. I would wrap the code in a #define of the form COMPILE_FAIL("error message");

Thanks D

Upvotes: 23

Views: 26797

Answers (3)

Rapptz
Rapptz

Reputation: 21317

Look into static_assert.

Example:

#include <iostream>
#include <type_traits>

template<typename T>
class matrix {
    static_assert(std::is_integral<T>::value, "Can only be integral type");
};

int main() {
    matrix<int*> v; //error: static assertion failed: Can only be integral type
}

Upvotes: 26

user529758
user529758

Reputation:

To force a compiler error (GCC, Clang style):

#error "You ain't finished this yet!"

Upvotes: 5

nneonneo
nneonneo

Reputation: 179717

Use #error:

#error "YOUR MESSAGE"

This produces an error from the preprocessor. If you want to detect an error at a later stage (e.g. during template processing), use static_assert (a C++11 feature).

Upvotes: 43

Related Questions