简体   繁体   English

在C ++中扩展类型

[英]Extending a type in C++

Sadly, UFCS did not make it into C++17 and that left me with a recurring problem: Sometimes I want to give types extra functionality using the method call syntax (without writing global functions). 遗憾的是,UFCS没有进入C ++ 17,这给我带来了一个反复出现的问题:有时我想使用方法调用语法给类型提供额外的功能(不需要编写全局函数)。 That would especially come handy when dealing with monads. 在处理monad时,这尤其方便。

I see two options: One is inheritance, and the other is encapsulation. 我看到两个选项:一个是继承,另一个是封装。 Because you cannot safely inherit from STL containers, that leaves encapsulation. 因为您无法安全地从STL容器继承,所以会留下封装。 For example, I want to extend std::optional , so I write: 例如,我想扩展std::optional ,所以我写道:

template <typename T>
struct myoption {
    // Some functionality
private:
    std::optional<T> impl;
};

My problem is that every time I want to do this, I basically have to write all the constructors (and needed methods that you can use with the original type, like push_back for vectors) the original type has. 我的问题是,每次我想要这样做,我基本上必须编写原始类型具有的所有构造函数(以及可以与原始类型一起使用的所需方法,如向量的push_back )。 Even a simpler container, like optional has 9 constructors. 即使是更简单的容器,也可选有9个构造函数。 When using inheritance, I can simply 'inherit' the methods and constructors of a super-class. 使用继承时,我可以简单地“继承”超类的方法和构造函数。 Is there a way to make this easier using encapsulation? 有没有办法使用封装更容易?

I would implement it by using private inheritance: 我将通过使用私有继承来实现它:

#define MAKE_PUBLIC(method) using std::vector<T>::method

template <typename T>
struct My_vector : private std::vector<T> {
    MAKE_PUBLIC(push_back);
    MAKE_PUBLIC(pop_back);
};

int main() {
    My_vector<int> v;
    v.push_back(3);
    std::vector<int>* vec = new My_vector<int>; // won't compile
}

This way, you can make sure that you cannot create objects with dynamic type of My_vector and reduce the effort to make inherited methods accessible by a mere macro (or using directive) instead of creating forward functions for each member function and overload. 这样,您可以确保无法创建具有动态类型My_vector对象,并减少仅通过宏(或使用指令)访问继承方法的工作量,而不是为每个成员函数和重载创建转发函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM