如何避免传递函数
How to avoid pass-through functions
我目前正在处理的一个 class 有一个定义各种函数的类型的成员。由于各种原因(例如,使其线程安全),我的 class 应该是这种类型的包装器。不管怎样,有些类型的功能可以直接通过,如下所示:
class MyClass {
// ... some functions to work with member_
/* Pass through clear() function of member_ */
void clear() {
member_.clear()
}
private:
WrappedType member_;
};
这还不错,而且我可以很灵活地向 MyClass::clear()
添加更多功能,以备不时之需。然而,如果我有一些这样的传递函数,它会膨胀 MyClass
并且对我来说会更难阅读。
所以我想知道是否有一种很好的单行方式(除了将上层定义写成一行)通过 WrappedType
的成员函数,很像 making base class members available:
/* Pass through clear() in an easier and cleaner way */
using clear = member_.clear; // Unfortunately, this obviously doesn't compile
从您的基础 class 私有继承并使用 using
关键字公开接口的子集:
class MyClass : private WrappedType
{
public:
using WrappedType::clear;
};
我目前正在处理的一个 class 有一个定义各种函数的类型的成员。由于各种原因(例如,使其线程安全),我的 class 应该是这种类型的包装器。不管怎样,有些类型的功能可以直接通过,如下所示:
class MyClass {
// ... some functions to work with member_
/* Pass through clear() function of member_ */
void clear() {
member_.clear()
}
private:
WrappedType member_;
};
这还不错,而且我可以很灵活地向 MyClass::clear()
添加更多功能,以备不时之需。然而,如果我有一些这样的传递函数,它会膨胀 MyClass
并且对我来说会更难阅读。
所以我想知道是否有一种很好的单行方式(除了将上层定义写成一行)通过 WrappedType
的成员函数,很像 making base class members available:
/* Pass through clear() in an easier and cleaner way */
using clear = member_.clear; // Unfortunately, this obviously doesn't compile
从您的基础 class 私有继承并使用 using
关键字公开接口的子集:
class MyClass : private WrappedType
{
public:
using WrappedType::clear;
};