Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alias a member function in class space?

I would like to be able to call the same member function by multiple names from an object of the class.

For example:

#include <string>
#include <stdio.h>

class Log
{
public:
    Log(std::string str)
        : log(str)
    {}

    void print() const
    {
        puts(log.c_str());
    }
    const auto& output = print;    // attempting to alias. does not work

private:
    std::string log;
};

int main()
{
    Log log("LOG: Log started.");
    log.print();
    log.output();    // both should call the same function.
    return 0;
}

This code yields this error for me (gcc 7.3.0)

main.cpp:15:15: error: non-static data member declared with placeholder ‘const auto’
         const auto& output = print;    // attempting to alias. does not work
               ^~~~
main.cpp: In function ‘int main()’:
main.cpp:25:13: error: ‘class Log’ has no member named ‘output’
         log.output();    // both should call the same function.

How can I define an alias for a function name?

like image 759
stimulate Avatar asked Sep 04 '26 05:09

stimulate


1 Answers

I would go with variadic template with perfect forwarding

class Log
{
public:
    Log(std::string str)
        : log(str)
    {}

    void print() const
    {
        puts(log.c_str());
    }

    template<typename... Ts>
    auto output(Ts&&... ts) const -> decltype(print(std::forward<Ts>(ts)...))
    {
        return print(std::forward<Ts>(ts)...);
    }

private:
    std::string log;
};

If signature of print changes, there is no need to change anything in output (apart from constness, that has to be changed accordingly). The only issue is verboseness of output signature and duplication of call to print in trailing return type (which is unnecessary in C++14). The good thing is that it works even if another overload of print is added! Another issue would be in IDE, which wouldn't forward documentation comments.

Another option would be to introduce member variables referencing the function.

like image 73
Zereges Avatar answered Sep 06 '26 19:09

Zereges