代码之家  ›  专栏  ›  技术社区  ›  stimulate

如何在类空间中别名成员函数?

  •  0
  • stimulate  · 技术社区  · 6 年前

    我希望能够从类的对象中通过多个名称调用同一成员函数。

    例如:

    #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;
    }
    

    这段代码为我产生了这个错误(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.
    

    如何为函数名定义别名?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Zereges Parveen Prajapati    6 年前

    我会选择带有完美转发的可变模板

    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;
    };
    

    如果签名 print 改变,没有必要改变 output (除了 const ness,那必须相应地改变)。唯一的问题是 输出 签署和复制 呼叫 以尾随返回类型打印(这在C++ 14中是不必要的)。好的是,即使另一个超负荷的 打印 已添加!另一个 问题 会在IDE中,但不会 向前地 文件注释。

    另一个选择是引入引用函数的成员变量。

        2
  •  4
  •   R Sahu    6 年前

    据我所知,该语言不提供为成员函数定义别名的机制。

    但是,如果愿意使用调用成员函数的非成员函数,则可以定义别名。

    #include <string>
    #include <stdio.h>
    
    namespace MyApp
    {
       class Log
       {
          public:
             Log(std::string str)
                : log(str)
             {}
    
             void print() const
             {
                puts(log.c_str());
             }
    
          private:
             std::string log;
       };
    
       void print(Log const& log)
       {
          log.print();
       }
    
       auto& output = print; // OK
       auto& write = print;  // OK
    }
    
    int main()
    {
       MyApp::Log log("LOG: Log started.");
       MyApp::print(log);  // Works OK
       MyApp::output(log); // Works OK
       MyApp::write(log);  // Works OK
       return 0;
    }