1

所以我试图用辅助方法构造一个类,即:

class Type{
    int a, b, c;

    friend auto helper(auto);
    friend auto test_helper(auto);
    /* couples test with implement */

public:
    void method(){
        helper(this);
    }
};

但是helper,如果我们想测试,创建一个朋友函数会将测试与实现结合起来helper

所以我想做helper一个免费的功能,即:

auto helper(int&,int&,int&);
auto test_helper(int&,int&,int&);

class Type{
    int a, b, c;
public:
    void method(){
        helper(a,b,c);
    }
};

然而,当数据成员很多时,这会使代码变得更加乏味。所以,我想出了一个想法来构建一个辅助结构,它具有精确的数据成员,Type但所有数据成员都是公共的,这样我们就可以简单地传递这样的句柄HelperType,也许是这样的:

struct HelperType{
    int a, b, c;
};
auto helper(HelperType* a);
auto test_helper(HelperType* a);
void Type::method(){
    helper(static_cast<HelperType*>(this));
}

有没有什么优雅的方法来构造这样的HelperType结构?例如通用包装器或可能具有继承?

4

1 回答 1

0

我没有简单的解决方案可以创建HelperTypeType只有想到的事情涉及繁重的元编程或宏使用)。然而,使用Type继承HelperType将非常简单private。从派生类(cppreference.com)

当一个类使用私有成员访问说明符从基类派生时,基类的所有公共和受保护成员都可以作为派生类的私有成员访问。

// Could be renamed "TypePrivateMembers" or "TypeData"
struct HelperType{
    int a, b, c;
};

auto helper(HelperType* a);

class Type : private HelperType {
public:
    // a,b,c can be accessed in Type class scope.

    void method(){
        helper(this);
    }
};

现场演示

但是,仍然来自 cppreference (强调我的):

私有继承也可以用来实现组合关系(基类子对象是派生类对象的一个​​实现细节)。使用成员可以提供更好的封装,并且通常是首选,除非派生类需要访问基的受保护成员(包括构造函数),需要覆盖基的虚拟成员,需要在其他基之前构建基并在其他基之后销毁子对象,需要共享一个虚拟基础或者需要控制一个虚拟基础的构建。[...]

这是关于继承辩论的反复组合。这个问题已经在 StackOverflow 上被问过很多次了,这里有一些关于这个主题的有趣链接(一般来说&对于这个特定的案例):

于 2018-07-08T22:38:42.553 回答