How to simplify interface declaration in C ++?

My interface declarations usually (always?) Follow the same pattern. Here is an example:

class Output
{
public:
    virtual ~Output() { }

    virtual void write( const std::vector<char> &data ) = 0;

protected:
    Output() { }

private:
    Output( const Output &rhs ); // intentionally not implemented
    void operator=( const Output &other );  // intentionally not implemented
};

The template is always the same: a public virtual destructor, a few simple virtual methods that make up the actual interface. default protected ctor, disabled copy and copy destination. I started using two small helper macros that can be used to simplify the above.

ABSTRACT_BASECLASS_BEGIN(Output)
    virtual void write( const std::vector<char> &data ) = 0;
ABSTRACT_BASECLASS_END(Output)

Unfortunately, I did not find a good way to do this with just one macro. Even better, I would like to completely avoid macros. However, the only thing that occurred to me was the code generator, which is a bit overloaded for me.

++ - . , .

+3
4

. , . - , ; .

; , , , .

- *pBase1 = *pBase2 ( -op), , , . , , .

:

class Output
{
public:
    virtual ~Output() {}
    virtual void write( const std::vector<char> &data ) = 0;
};
+3

:

class NoncopyableBase
{
public:
    NoncopyableBase() { }
    virtual ~NoncopyableBase() { }
private:
    NoncopyableBase(const NoncopyableBase&);
    void operator=(const NoncopyableBase&);
};

, , .

+3

, .

IMO, . :

#include <vector>

#define DEFAULT_CLASS_METHODS(C) public: \
        virtual ~C(){}; \
    protected: \
        C(){}; \
    private: \
        inline C(const C& rhs){}; \
        inline void operator=(const C& other){}; 

class Output{
    DEFAULT_CLASS_METHODS(Output)
public:
    virtual void write(const std::vector<char> &data) = 0;
};

*.h. , - *.cpp, , .

, .

, :

#include <vector>

#define BEGIN_INTERFACE(C) class C{ \
    public: \
        virtual ~C(){}; \
    protected: \
        C(){}; \
    private: \
        inline C(const C& rhs){}; \
        inline void operator=(const C& other){}; 

BEGIN_INTERFACE(Output)
public:
    virtual void write(const std::vector<char> &data) = 0;
};

, {, .

+3

- :

ABSTRACT_BASECLASS(Output,
    (virtual void write( const std::vector<char> &data ) = 0;)
    (more methods))

(first)(second)(...)is the boost preprocessor sequence, which is really the only argument for your macro: http://www.boost.org/doc/libs/1_43_0/libs/preprocessor/doc/index.html p>

#define BASECLASS(name, methods) \
...\
BOOST_PP_SEQ_CAT(methods)\  //will concatenate methods declarations
...\
+2
source

Source: https://habr.com/ru/post/1757505/


All Articles