我有一个 FooBar
类,其中包含 Foo
类型的成员。可以继承此类型,以便 FooBar
具有可变的行为。 Foo
包含访问器方法 bar
的多个重载。
class FooBar;
class Foo{
friend class FooBar;
virtual void bar(int barIn){ bar_ = barIn; }
virtual void bar(int barIn, float barScale){ bar(int(barIn * barScale)); }
virtual void bar(const Foo& barSource){ bar(barSource.bar_); }
int bar(){ return bar_; }
int bar_;
};
class FooBar{
public:
void bar(int barIn){ foo_.bar(barIn); }
void bar(int barIn, float barScale){ foo_.bar(barIn, barScale); }
void bar(const Foo& barSource){ foo_.bar(barSource); }
int bar(){ return foo_.bar(); }
private:
Foo& foo_;
};
到目前为止看起来还不错,但我觉得 FooBar.bar
访问器的所有定义都是不必要的。我知道编译器内联它们,所以应该没有开销,但是这些方法都具有相同的名称,并且都是彼此的重载。
C++ 中是否有一种方法可以“导出”(我没有找到更好的词)访问器,因此对 FooBar.bar
的调用仅重定向到 FooBar。 foo_.bar
?
我的一个想法是重写 FooBar
的 operator ->
,但实际情况有多个类,如 Foo
,所以这会只为其中之一工作。
最佳答案
您可以编写一个真正的通用转发器:
class FooBar
{
public:
template<typename... Args>
auto bar(Args&&... args) -> decltype(foo_.bar(std::forward<Args>(args)...))
{
return foo_.bar(std::forward<Args>(args)...);
}
private:
Foo& foo_;
};
(这需要 C++11,使用 C++14 您甚至可以省略 ->decltype...
部分)
关于c++ - 如何对C++中一个函数的所有重载进行 "export"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23443545/