⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

[Solved] Raise compilation errors

  • Hi,

    Is there a way to simply raise compilation errors?
    For example, in a template class, if I only want to accept pointers type, how can I raise a compilation errors to prevent the user to instantiate the template class with a static type? (Or the contrary)

    I'm looking for doing something like "qMetaTypeId":http://qt-project.org/doc/qt-5/qmetatype.html#qMetaTypeId which raises an error if the type isn't registered, do you guys have an idea?


    [andreyc: I moved it to C++ Gurus. I think the question is more about C++ then about Desktop development]

  • If you use C++ 11 then here is an example
    /** http://www.cplusplus.com/reference/type_traits/

    #include <iostream>
    #include <type_traits>

    template <class T>
    void test(T a, T b)
    static_assert(std::is_pointer<T>::value, "Test requires pointers");
    auto c = b;
    b = a;
    a = c;

    class A
    A() {}
    ~A() {}

    int main() {
    std::cout << std::boolalpha;
    std::cout << "is_pointer:" << std::endl;
    std::cout << "int: " << std::is_pointer<int>::value << std::endl;
    std::cout << "int*: " << std::is_pointer<int*>::value << std::endl;
    std::cout << "int**: " << std::is_pointer<int**>::value << std::endl;
    std::cout << "int()(int): " << std::is_pointer<int()(int)>::value << std::endl;

    int* pa = nullptr;
    int* pb = nullptr;
    test(pa, pb);

    A* paA = nullptr;
    A* pbA = nullptr;
    test(paA, pbA);

    A aA;
    A bA;
    test(&aA, &bA);
    test(aA, bA);

    int a = 0;
    int b = 10;
    test(a, b);

    return 0;

  • [quote author="andreyc" date="1401231833"]http://en.cppreference.com/w/cpp/language/static_assert[/quote]

    Oh thanks ! I didn't know about static_assert.

    There also are: Q_STATIC_ASSERT(condition) and Q_STATIC_ASSERT_X(bool, message)

Log in to reply