Standard way of shortening C++ function signatures

时间:2015-05-30 19:24:59

标签: c++ templates stl function-declaration

The templates always get really lengthy when I have certain vector and templated contained objects and the end just looks like a bunch of > > > > > > > that hardly helps discern boundaries sometimes, like this:

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

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

I have tried shortening the function name and typedef-ing 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 个答案:

答案 0 :(得分:4)

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

Type aliases using typedef can be 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 between >>, you don't need after < or before >:

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

UPDATE

As @Snowhawk04@mkrieger1 使用现代编译器,您不再需要>>之间的空格。 只要确保使用正确的编译器标志, 例如-std=c++0xg++。 查看更多信息about >>template aliases

答案 1 :(得分:4)

作为一个额外的答案,在C ++ 11中,您可以使用using代替typedef,两者都可以完成同样的事情:

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

答案 2 :(得分:1)

您也可以创建一个在返回类型后中断的新行。这就是像Clang-Format这样的格式化工具。

struct EventMaker {
    virtual ~EventMaker() {};

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

C ++ 11还引入了 Trailing-Return-Type 。有些人发誓在其预定用途之外讨厌它。

struct EventMaker {
    virtual ~EventMaker() {};

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

不幸的是,我们不能在虚函数上使用C ++ 14的自动返回类型扣除,因为返回类型是它与派生类的契约的一部分。

除非您打算编写多语言代码(即extern "C"{};),否则可以省略不带参数的函数的void参数。