Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ decltype how to use to simplify variable definition

Tags:

c++

c++11

Say, I have this piece of code, in one of my classes, that defines

  • A map of key and another map
  • The second map is another key and a function handler
  • The function hander is a signature that takes 2 params

Right now, the signature to define the variable looks incredible.

std::map<std::string, std::map<std::string,
    std::function<void(std::shared_ptr<HTTPRequest>,
        std::shared_ptr<HTTPResponse>)>>> routeFunctions_;

I recently came to know about decltype, but unable to use this correctly.

decltype(x) routeFunctions_;  // What should be there in the place of x ?
like image 643
Mopparthy Ravindranath Avatar asked May 28 '26 11:05

Mopparthy Ravindranath


1 Answers

  • Use typedef to this type, if you often declare variables of it.
  • Use auto or decltype, if you want to return value of this type from a function.
  • Use decltype, if you want to get type of structure/class member.

Look at this articles:

http://en.cppreference.com/w/cpp/language/auto http://en.cppreference.com/w/cpp/language/decltype

http://www.cprogramming.com/c++11/c++11-auto-decltype-return-value-after-function.html

Your choice in this case is a typedef:

typedef std::map<std::string, std::map<std::string,
std::function<void(std::shared_ptr<HTTPRequest>,
std::shared_ptr<HTTPResponse>)>>> RouteFunctionsContainer;

RouteFunctionsContainer routeFunctions_;
like image 144
A.N. Avatar answered May 31 '26 07:05

A.N.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!