Frank
Frank

Reputation: 2696

Function alias for function with default argument

I want to use a alias for a function with a default argument:

class Foo
{
  static void bar(int i, int j=0);
};

const auto aliasFunction = Foo::bar;

However when I try to call this by calling aliasFunction(1) the compiler complains that the function takes two arguments. Is there an easy fix for this?

Upvotes: 2

Views: 593

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

You can use either a lambda to do this:

auto aliasFunction = [](int i)
{
    return Foo::bar(i);
};

Or using std::bind (which kind of deprecated in favor of lambdas):

using namespace std::placeholders;  // For _1
auto aliasFunction = std::bind(&Foo::bar, _1, 0);

However it's not possible to create a true alias of a function (your definition doesn't create an alias either. but a pointer).


For completeness, but not recommended, it's of course possible to use the preprocessor and create a macro:

#define aliasFunction(i) Foo::bar(i)

Upvotes: 3

Related Questions