sti*_*ate 2 c++ alias class function member-functions
我希望能够从类的对象中通过多个名称调用相同的成员函数。
例如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
此代码为我产生此错误(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.
Run Code Online (Sandbox Code Playgroud)
如何为函数名称定义别名?
我会使用带有完美转发的可变参数模板
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;
};
Run Code Online (Sandbox Code Playgroud)
如果签名print更改,则无需更改任何内容output(除了constness,必须相应地更改)。唯一的问题是output签名的冗长和尾随返回类型中打印的重复调用(这在 C++14 中是不必要的)。好消息是,即使print添加了另一个重载,它也能工作!另一个问题是在 IDE 中,它不会转发文档注释。
另一种选择是引入引用函数的成员变量。