(对于类型擦除,我的意思是隐藏有关类的一些或所有类型信息,有点像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) #include <functional>
void toggleOk(bool& b) { b = !b; }
void toggleBroken(bool b) { b = !b; }
void toggleInt(int i) { i = !i; }
void tooManyParams(bool b, int i) { i = !b; }
int main()
{
typedef std::function<void(bool&)> CallbackType;
typedef std::function<void(bool)> WrongCallbackType;
CallbackType cb1 = [](bool b) { b = !b; }; // Should throw error - missing reference
CallbackType cb2 = toggleOk; // Ok
CallbackType cb3 = toggleBroken; // Should throw error - missing reference
CallbackType …Run Code Online (Sandbox Code Playgroud) 是否可以将foo从float转换为long(反之亦然)?
auto foo = float(1234567891234.1234);
cout << "foo: " << foo << endl;
foo = long(1234567891234.1234);
cout << "foo: " << foo << endl;
Run Code Online (Sandbox Code Playgroud)
输出总是:
foo: 1.23457e+12 foo: 1.23457e+12
我有以下结构:
template <typename T>
struct A
{
T t;
};
Run Code Online (Sandbox Code Playgroud)
在另一个结构中,我想定义一个指向结构 A 的指针:
struct B
{
//A* a;
};
Run Code Online (Sandbox Code Playgroud)
类型 A 的对象的特定类型将在对象 A 创建期间已知。如何在 struct B 中定义指向模板类型的指针?