Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "using" for a function?

Tags:

c++

c++11

using

How to use "using" for a function? For example

class A;
void f(int);

struct B
{
   using BA = A;
   using Bf = f; ???
};
like image 359
user1899020 Avatar asked Jan 20 '17 20:01

user1899020


People also ask

How do you use a function?

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.

What does () => mean in JavaScript?

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.


2 Answers

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.

like image 171
Nir Friedman Avatar answered Sep 30 '22 04:09

Nir Friedman


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.

like image 37
Barry Avatar answered Sep 30 '22 04:09

Barry