Standard way to shorten C ++ function signatures

Templates always get really long when I have certain vector and templated contained objects, and the end looks like a heap > > > > > > >

, which hardly helps distinguish borders sometimes:

std::vector< std::pair< std::string, std::set< std::string > > >

      

Is there a standard way to reduce the length or to make the elements easily distinguishable? My actual code is this class declaration.

I tried to shorten the function name and print the return value.

class Event_Maker
{
    public:

        virtual ~Event_Maker() {};

        // this one                                    *this juts out really far   v
        virtual std::vector< std::unique_ptr< Event > > transfer_events( void ) = 0;
};

      

+3


source to share


3 answers


Is there a standard way to reduce the length or to make the elements easily distinguishable?

Typical aliases using typedef

might come in handy, for example:

typedef std::unique_ptr<Event> EventPtr;
typedef std::vector<EventPtr> EventVector;
virtual EventVector transfer_events( void ) = 0;

      

Btw, you only need a space in between >>

, you don't need after <

or before >

:



std::vector<std::pair<std::string, std::set<std::string> > >

      

UPDATE

As @ Snowhawk04 and @ mkrieger1 pointed out in the comments, with modern compilers you no longer need space in between >>

. Just make sure you are using the correct compiler flags such -std=c++0x

as g++

. More information about>>

and template aliases .

+4


source


As a complementary answer in C ++ 11, you can use using

instead typedef

, both accomplish the same thing:



//typedef pair<string, set<string>> pairStrSetStr;
using pairStrSetStr = pair<string, set<string>>;
vector<pairStrSetStr> vec;

      

+4


source


You can also just create a new line that breaks after the return type. This is what formatting tools like Clang-Format do.

struct EventMaker {
    virtual ~EventMaker() {};

    virtual std::vector<std::unique_ptr<Event>> 
    transfer_events() = 0;
};

      

C ++ 11 also introduced a return type. Some people swear to hate it outside of their intended use.

struct EventMaker {
    virtual ~EventMaker() {};

    virtual auto transfer_events() 
    -> std::vector<std::unique_ptr<Event>> = 0;
};

      

Unfortunately, we cannot use C ++ 14 Auto Return Type Deduction for virtual functions as the return type is part of the contract it has with derived classes.

Unless you plan on writing multilingual code (i.e. extern "C"{};

), you can omit parameters void

for functions that take no arguments,

+1


source







All Articles