How to use "using" for a function? For example
class A;
void f(int);
struct B
{
using BA = A;
using Bf = f; ???
};
To call a function (which is another way to say “tell the computer to follow the step on this line of the directions”), you need to do four things: Write the name of the function. Add parentheses () after the function's name. Inside the parenthesis, add any parameters that the function requires, separated by commas.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
You can do
struct B
{
using BA = A;
constexpr static auto Bf = f;
}
That way you don't have to worry about specifying the type, which can be annoying.
You don't want to declare a non-static variable, otherwise every single copy of your object will be carrying around a function pointer. You also don't want it to be mutable, because then you can reassign it. You also don't want it to be potentially determined at runtime, because then the compiler will have to prove to itself in a given context that a call to Bf
is really calling f
, or else pay function indirection costs. The constexpr
handles these last two points.
If f
is just a function, you could either add a member function pointer:
void (*Bf)(int) = f;
or just wrap it in a function:
void Bf(int i) { f(i); }
Probably prefer the latter though, as it avoids adding extra members to B
.
If f
is a function template, you can't just alias, you'd need to forward to it:
template <class... Args>
auto Bf(Args&&... args)
-> decltype(::f(std::forward<Args>(args)...))
noexcept(noexcept(::f(std::forward<Args>(args...))))
{
return ::f(std::forward<Args>(args)...);
}
which is... yeah.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With