(对于类型擦除,我的意思是隐藏有关类的一些或所有类型信息,有点像Boost.Any.)
我想要掌握类型擦除技术,同时也分享那些,我知道.我希望找到一些有人在他/她最黑暗的时刻想到的疯狂技巧.:)
我所知道的第一个也是最明显的,也是最常用的方法是虚函数.只需在基于接口的类层次结构中隐藏类的实现.许多Boost库都这样做,例如Boost.Any这样做是为了隐藏你的类型,而Boost.Shared_ptr这样做是为了隐藏(de)分配机制.
然后有一个函数指针指向模板化函数的选项,同时将实际对象保存在void*指针中,如Boost.Function确实隐藏了仿函数的实际类型.可以在问题的最后找到示例实现.
所以,对于我的实际问题:
你知道其他什么类型的擦除技术?如果可能的话,请提供示例代码,用例,您对它们的体验以及可能的进一步阅读链接.
编辑
(因为我不确定是否将此作为答案添加,或者只是编辑问题,我只会做更安全的问题.)
另一个很好的技术来隐藏没有虚函数或void*摆弄的东西的实际类型,是一个GMan在这里工作,与我的问题有关,这个问题究竟是如何运作的.
示例代码:
#include <iostream>
#include <string>
// NOTE: The class name indicates the underlying type erasure technique
// this behaves like the Boost.Any type w.r.t. implementation details
class Any_Virtual{
struct holder_base{
virtual ~holder_base(){}
virtual holder_base* clone() const = 0;
};
template<class T>
struct holder : holder_base{
holder()
: held_()
{} …Run Code Online (Sandbox Code Playgroud) MyFunc(int, double, string)我的项目中有一个已实现的功能.例如,如何使用具有其字符串表示的必要参数来调用此函数
std::string str = "MyFunc(2, 3.12, \"Lemon Juice\")";
Run Code Online (Sandbox Code Playgroud)
并且怎么样的标准功能,例如,我怎么能调用time()有std::string "time()"?
好的,这是更详细的任务.我有一个map <string, Data>
Data包含许多孩子的类包装器.当我调用Data.GetValue()方法时,它返回一个std::string,取决于子类内部数据.其中一个子项Data必须返回int另一个字符串表示形式 - 字符串表示形式double,最后一个 - 当前日期和时间的字符串表示形式.这是问题 - 我不知道如何调用标准函数ctime()来获取其中一个Data孩子的信息.
这与前一个问题有关:使用boost :: bind和boost :: function:检索绑定变量类型.
我可以绑定一个这样的函数:
在.h:
class MyClass
{
void foo(int a);
void bar();
void execute(char* param);
int _myint;
}
Run Code Online (Sandbox Code Playgroud)
在.cpp
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
myVector.push_back(boost::bind(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* param)
{
boost::function<void(void)> f = myVector[0];
_myint = atoi(param);
f();
}
Run Code Online (Sandbox Code Playgroud)
但是如何绑定返回值呢?即:
在.h:
class MyClass
{
double foo(int a);
void bar();
void execute(char* param);
int _myint;
double _mydouble;
}
Run Code Online (Sandbox Code Playgroud)
在.cpp
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
//PROBLEM IS HERE: HOW DO I BIND "_mydouble"
myVector.push_back(boost::bind<double>(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* …Run Code Online (Sandbox Code Playgroud) 我需要从c ++对象解析并生成一些文本.
语法是:
command #param #param #param
Run Code Online (Sandbox Code Playgroud)
有一组命令,其中一些没有参数等.参数主要是数字.
问题是:我应该使用Boost Spirit来完成这项任务吗?或者只是简单地将每行评估函数标记为从字符串比较命令,读取其他参数并从中创建cpp对象?
如果你建议使用Spirit或任何其他解决方案,如果你能提供一些与我的问题类似的例子,那将是很好的.我已阅读并尝试了Boost Spirit doc中的所有示例.
c++ ×4
boost ×1
boost-bind ×1
boost-spirit ×1
function ×1
parsing ×1
tokenize ×1
type-erasure ×1