user3414321 user3414321 - 2 months ago 22
C++ Question

How is class function without definition not causing error

I was learning some C++ idioms when I came across a sample code for SFINAE, I was perplexed with the code.

Note:

is_ptr()
has no definition.


  1. I compiled the code myself, no compiler errors regarding lack of function definition, why?

  2. sizeof()
    was used on one of the calls, it apparently executed on the returns of the functions, but then again, there was no definition. How was that possible?

    template <typename T>
    struct is_pointer
    {
    template <typename U>
    static char is_ptr(U*);

    template <typename X, typename Y>
    static char is_ptr(X Y::*);

    template <typename U>
    static char is_ptr(U (*)());

    static double is_ptr(...);

    static T t;
    enum {value = sizeof(is_ptr(t)) == sizeof(char)};
    };


Answer Source

sizeof is what is called an un-evaluated context. Within it the expression needs to be only well formed, nothing will actually ever be executed. So a function that is only declared can be used inside without needing an actual definition.

This is because the definition is not required to determine the type information. In this case, the overload that is chosen by ADL is the type information in question. It's return type is also available from the declaration alone.