Given the following setup:
// ***** Library Code *****
#include <concepts>
template <std::invocable CbT>
struct delegated {
explicit constexpr delegated(CbT cb) : cb_(std::move(cb)) {}
private:
[[no_unique_address]] CbT cb_;
};
// ***** User Code *****
#include <iostream>
namespace {
inline constexpr void func() {}
}
struct MyFunc {
constexpr void operator()() const {}
};
int main() {
void (*func_ptr)() = func;
auto from_func = delegated{func};
auto from_func_ptr = delegated{func_ptr};
auto from_lambda = delegated{[](){}};
auto from_functor = delegated{MyFunc{}};
std::cout << "func: " << sizeof(from_func) << "\n";
std::cout << "func_ptr: " << sizeof(from_func_ptr) << "\n";
std::cout << "lambda: " << sizeof(from_lambda) << "\n";
std::cout << "functor: " << sizeof(from_functor) << "\n";
}
It produces, on GCC-x86-64 (See on godbolt):
func: 8 <----- Unfortunate
func_ptr: 8 <----- Fair enough
lambda: 1 <----- Neat
functor: 1 <----- Neat
None of this is particularly surprising.
However, it's frustrating that an undecayed lambda is preferable to using a function. And adding a note that delegated{[]{func();}} reduces the storage overhead is not exactly user-friendly, and makes for a very poor library interface.
Is there a way to do away with the storage overhead in the func case while maintaining a consistent user-facing API?
My current suspicion is that this is not possible without resorting to macros, on account of func not having, or decaying into, any type that would distinguish it from other functions with the same signature. I'm hoping that I overlooked something.
N.B. I get that something along the lines of delegated<func>() is a possibility, but unless I can prevent delegated{func} while still allowing delegated{func_ptr}, then that would be practically pointless.
Edit: To clarify the context a little bit: I am writing delegated in a library, and I don't want users of said library to have to worry about this. Or at least have the process be compiler-assisted instead of being documentation-dependant.