Adam Badura
Adam Badura

Reputation: 5339

Declaring member function using function type syntax

Just recently I learned that you can declare a function (including methods) using variable-like syntax with function type:

using function_type = int (double);
// pre-C++11:
//typedef int function_type(double);

function_type fun_global;

struct methods
{
    static function_type mem_fun_static;
    function_type mem_fun_normal;
    virtual function_type mem_fun_virtual;
    virtual function_type mem_fun_abstract = 0;
};

In above code

All of them take single argument of type double and return int value - just like the function_type says.

All this years I know C++ and I didn't know about this - this language never stops surprising me! By the way - is this syntax mentioned anywhere here? I don't see this...

However, while exploring this new to me feature I stumbled upon some inconsistencies between compilers. For tests, I was using following compilers:

In tests that I run both GCC versions gave same result so further I'm referring to them just as GCC.


= delete inconsistency

struct methods
{
    /* ... */
    function_type mem_fun_deleted = delete;
};

= default inconsistency

struct methods
{
    /* ... */
    using assignment_type = methods& (methods const&);
    assignment_type operator= = default;
};

Inline definition inconsistency

struct methods
{
    /* ... */
    function_type mem_fun_inline { return 0; }
};

Questions

Which compilers are right here?

Furthermore, is it possible to:

  1. In the inline definition (supported only by MSVC) refer somehow to the argument?
  2. Somehow use the function_type also at definition of those functions (when done outside of the class). Following is OK (with all compilers)

    struct methods
    {
        static function_type mem_fun_static;
        /* ... */
    };
    
    int methods::mem_fun_static(double) { return 0; }
    

    It is not that bad since change of function_type should result in compilation error at function definition (as it will no longer match declaration) - but still maybe it is possible to avoid even that.

Upvotes: 10

Views: 1117

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119857

§ 8.3.5 Functions [dcl.fct] p12 A typedef of function type may be used to declare a function but shall not be used to define a function.

Thus Clang is right to reject the code in all cases and compilers that accept it are in the wrong.

(The quotation is from N4618 but the rule is a part of the language since forever).

Upvotes: 5

Related Questions