Integrate type name in static_assert output?

后端 未结 5 960
独厮守ぢ
独厮守ぢ 2020-12-04 18:56

I like to give helpful errors / messages, and I also want to do so for my static_asserts. The problem is, that they depend on template parameters. Normally, tho

5条回答
  •  日久生厌
    2020-12-04 19:44

    My Hack

    Code:

    template 
    struct AssertValue : AssertionChecker
    {
        static_assert(AssertionValue, "Assertion failed ");
        static bool const value = Assertion::value;
    };
    

    It allows for you to check any ::value assertion and dump the types if it failed.

    Usage:

    // Bad indentation used to show parts
    static_assert(
        AssertValue<
            std::my_check<
                T0, decltype(*somethingComplicated), T7::value_type
            >
        >, 
        "something horrible happened"
    );
    

    where std::my_check<...>::value is the boolean result of the check

    Example

    For a full SSCCE example see: IDEOne Example

    The Example's error message:

    prog.cpp: In instantiation of 'AssertValue >':
    prog.cpp:37:69:   instantiated from 'void MyFunction(IteratorType, IteratorType) [with IteratorType = __gnu_cxx::__normal_iterator >]'
    prog.cpp:60:38:   instantiated from here
    prog.cpp:9:5: error: static assertion failed: "Assertion failed "
    prog.cpp: In function 'void MyFunction(IteratorType, IteratorType) [with IteratorType = __gnu_cxx::__normal_iterator >]':
    prog.cpp:60:38:   instantiated from here
    prog.cpp:39:5: error: static assertion failed: "iterator passed does not reference IMyInterface items"
    

    Explanation

    If the assertion fails, it will print the template arguments of AssertValue and therefore print the full template expansion of your check. For example, if you were checking a std::is_base_of it will print the full type of the check, e.g.: std::is_base_of. Then you know exactly what types were used in the failed assertion.

    The only problem is that this only works on templates that put their result in ::value. However type_traits mostly uses this and is the goto standard.

提交回复
热议问题