在C ++中扩展类型 [英] Extending a type in C++

查看:62
本文介绍了在C ++中扩展类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可悲的是,UFCS并未将其纳入C ++ 17,这给我带来了一个反复出现的问题: 有时我想使用方法调用语法为类型提供额外的功能(不编写全局函数).与单子打交道时,这特别方便.

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). That would especially come handy when dealing with monads.

我看到两个选项:一个是继承,另一个是封装.因为您不能安全地从STL容器继承,所以留下了封装.例如,我想扩展std::optional,所以我写:

I see two options: One is inheritance, and the other is encapsulation. Because you cannot safely inherit from STL containers, that leaves encapsulation. For example, I want to extend std::optional, so I write:

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

我的问题是,每次我想执行此操作时,基本上都必须编写原始类型具有的所有构造函数(以及可以与原始类型一起使用的所需方法,例如用于向量的push_back).甚至更简单的容器(如可选)也具有9个构造函数.使用继承时,我可以简单地继承"超类的方法和构造函数.有没有办法使封装更容易?

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. Even a simpler container, like optional has 9 constructors. 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
}

这样,您可以确保不能创建 dynamic 类型为My_vector的对象,并减少了使仅由宏(或使用指令)访问继承方法而不是创建继承方法的工作.每个成员函数和重载的正向函数.

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.

这篇关于在C ++中扩展类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆