我编写了以下类来查找关键字并执行关联的函数。
#include <iostream>
#include <string>
#include <map>
class Example;
typedef std::map<
std::string, void (Example::*)(const std::string &)> ExampleList;
typedef ExampleList::iterator ExampleIter;
class Example
{
public:
ExampleList lut;
Example()
{
lut["aaa"] = &Example::aaa;
lut["bbb"] = &Example::bbb;
}
void lookup(const std::string& line)
{
// Get the keyword
std::size_t keylen = line.find(' ', 0);
std::string keyword = line;
if (keylen != line.npos)
keyword = line.substr(0, keylen);
// Is it something we recognize
ExampleIter eit = lut.find(keyword);
if (eit == lut.end())
{
std::cout << "Unable to handle " << keyword << std::endl;
return;
}
// Found - execute the handler
(this->*(eit->second))(line); // << is there an alternative syntax without this?
}
void aaa(const std::string& info)
{
std::cout << "aaa" << std::endl;
}
void bbb(const std::string& info)
{
std::cout << "bbb" << std::endl;
}
};
int main()
{
Example eg;
eg.lookup("aaa"); // pass
eg.lookup("bbb is legal"); // pass
eg.lookup("bbbb is illegal"); // fail - bbbb not found
eg.lookup("cc"); // fail cc not found
eg.lookup("aaaa"); // fail aaaa not found
}
在函数查找结束时,我使用
执行处理程序(this->*(eit->second))(line);
我只是想知道是否可以在没有
this->*
的情况下调用处理程序
No:指向成员的指针,即使是当前类类型的成员,也没有成员本身具有的隐式
(*this).
(或者更确切地说,他们需要的(*this).*
)。从根本上来说,这是因为不可能(可靠地)区分指针的使用和引用成员的使用:
struct X {
int i;
auto f() {
int X::*p=&X::i;
return p; // does this return 'int X::*' or 'int'?
}
};
直接成员访问不会出现这种歧义,因为您必须使用
&X::i
而不仅仅是 &i
来形成指向成员的指针。还要考虑到这样一个指向成员的指针可能指向 衍生 类的成员,而 *this
甚至没有。