我有一个类可以解析文档并调用派生类来通知在流中找到的某些事件。因为解析器必须处理编码并将部分文档重新写入字符串,所以如果虚拟方法没有被覆盖,我想避免重写。伪代码:
class Parser
{
virtual void Callback ( string )
{
// Do nothing
}
private:
void ParseFile()
{
// Parse the file in the files encoding
// Checks and more checks
// Found sth. So need to convert to a string a call the
// callback, but if there is no callback what's the point
// in wasting cycles?
if ( Callback ) // In the world of C we could check for a func pointer
Callback( /* with the string */ )
}
}
class User : public Parser
{
void Callback ( string )
{
// This string means sth. me
}
}
class NonUser : public Parser
{
// I don't care about Callback so I won't implement it
}
在 C 代码中,我们将编写一个函数并将指向该函数的指针传递给实现。在内部,它会检查指针是否指向某个东西并调用它。派生类如何实现相同的功能?IE。在浪费时间/CPU周期/内存构造一个甚至可能不需要的字符串之前检查虚拟方法是否实际存在于派生类中。
编译时间检查(如果它是可移植的)将是理想的,但我认为这与 v-tables 有关,因此运行时间检查也可能有效。
经过更多的研究,很明显 v-tables 已经过时了,这几乎是不可能的。我会稍微改变我的问题,问上面是否可能使用某种类型的,也许是模板,诡计?