Home > Software engineering >  Is it valid to use std::function with incomplete types?
Is it valid to use std::function with incomplete types?

Time:01-31

I wondered if it is valid to use std::function with incomplete type, e.g. in case of forward declaration. I wrote this small code:

#include <iostream>
#include <functional>

struct S;

std::function<S(void)> m;

struct S {
    S() { std::cout << "ctor\n"; }
    ~S() { std::cout << "dtor\n"; }
    void foo() { std::cout << "foo\n";}
};

S goo() {
    return S{};
}

int main() {
    m = goo;
    m().foo();
}

Even though the S is incomplete in the point of declaring m, I could declare return type like a complete type(a non-pointer return type). This code complies and works correctly, but I'm not sure if this code is valid by standard. Because you cannot forward declare return type if it is not a pointer in a normal function(so I cannot forward declare S for goo()).

Any idea if this is a valid code by standard or not?

CodePudding user response:

Any idea if this is a valid code by standard or not?

The program is well-formed because even though S is incomplete at the point of the definition std::function<S(void)> m;, the std::function doesn't place any requirement on S to be a complete type and instead requires that S be the name of a return type.

From std::function's documentation:

The function class template provides polymorphic wrappers that generalize the notion of a function pointer. Wrappers can store, copy, and call arbitrary callable objects, given a call signature, allowing functions to be first-class objects.

The above means that the template argument should be in the form of a call signature. From call signature's documentation:

A call signature is the name of a return type followed by a parenthesized comma-separated list of zero or more argument types.

(emphasis mine)

As we can see the above requires that S be the name of a return type. That is, it doesn't explicitly place any requirement on S being complete.

In other words, S in your given examples satisfies this condition so that it is valid.

  • Related