我发现了类似于这样的代码:
typedef std::map<std::string, Example*(*)()> map_type;
经过一段时间的搜索,我仍然无法确切地了解 (*) 运算符的作用。 有人有任何想法吗?
typedef std::map<std::string, Example*(*)()> map_type;
经过一段时间的搜索,我仍然无法确切地了解 (*) 运算符的作用。 有人有任何想法吗?
Example*(*)()
这是一个指向返回 Example
指针的函数的指针。
如果没有括号,你会得到
Example**()
Example
。typedef Example* (*myFunctionType)();
这将使该行
typedef std::map<std::string, myFunctionType> map_type;
要确切地等同于您给出的行。请注意,Example* (*myFunctionType)()
和Example* (*)()
之间的区别仅在于类型名称被省略。
#include <string>
#include <map>
typedef int Example;
Example* myExampleFunc() {
return new Example[10];
};
typedef std::map<std::string, Example*(*)()> map_type;
int main() {
map_type myMap;
// initializing
myMap["key"] = myExampleFunc;
// calling myExampleFunc
Example *example = myMap["key"]();
return 0;
}
因为模板typedef的存在,您可以在C++11中使复杂的指针类型变得不那么混乱:
template<typename T> using ptr = T*;
typedef std::map<std::string, ptr<Example*()>> map_type;