Alternative to `#define` macro for function alias in C++

843 Views Asked by At

fmtlib has a function like:

template <typename S, typename... Args, typename Char = char_t<S>>
inline std::basic_string<Char> format(const S& format_str, Args&&... args) {
  return internal::vformat(
      to_string_view(format_str),
      {internal::make_args_checked<Args...>(format_str, args...)});
}

I've defined a macro for my convenience like:

#define FMT fmt::format

I use it like:

std::cout<<FMT("Name: {0}\n", "Joe");

Is there an alternative to using macro for this in C++11, preferably one that doesn't hit performance?

2

There are 2 best solutions below

2
On BEST ANSWER

You can define the same function with a shorter name (in your own code). This function is named FMT() and it passes its parameters to fmt::format(), which is the original function you want to call:

template <typename S, typename... Args, typename Char = fmt::char_t<S>>
inline std::basic_string<Char> FMT(const S& format_str, Args&&... args) {
  return fmt::format(format_str, std::forward<Args>(args)...);
}

Demo

0
On

If you want to introduce a symbol from namespace you can use using.

If you want to make an easier to type alias for a function, you can use auto& or auto or auto&& or auto const&.

Or you could use a lamdba wrapper.

Any of which are better choices than a function-like macro, in my opinion.

#include <iostream>

using std::cout;

namespace Happy {

void Joy();

void Joy() {
    cout << "Joy and pride!\n";
}

} // Happy

int main() {
    // Example of using.
    using Happy::Joy;
    Joy();

    // Example of aliasing.
    auto& pride = Happy::Joy;
    auto pride2 = Happy::Joy;
    auto&& pride3 = Happy::Joy;
    auto const& pride4 = &Happy::Joy;
    pride();
    pride2();
    pride3();
    pride4();

    // Example of wrapping in a lambda.
    auto lambda = []{ Happy::Joy(); };
    lambda();
}