如果您阅读 boost::any 文档,它们会提供该想法的来源:http: //www.two-sdg.demon.co.uk/curbralan/papers/ValuedConversions.pdf
这是基本的信息隐藏,是必备的 C++ 技能。学习吧!
由于这里投票得最高的答案是完全不正确的,而且我怀疑人们是否真的会去查看源代码来验证这一事实,这里有一个 any like 接口的基本实现,它将用 f() 函数包装任何类型和允许它被调用:
struct f_any
{
f_any() : ptr() {}
~f_any() { delete ptr; }
bool valid() const { return ptr != 0; }
void f() { assert(ptr); ptr->f(); }
struct placeholder
{
virtual ~placeholder() {}
virtual void f() const = 0;
};
template < typename T >
struct impl : placeholder
{
impl(T const& t) : val(t) {}
void f() const { val.f(); }
T val;
};
// ptr can now point to the entire family of
// struct types generated from impl<T>
placeholder * ptr;
template < typename T >
f_any(T const& t) : ptr(new impl<T>(t)) {}
// assignment, etc...
};
boost::any 做同样的基本事情,除了 f() 实际返回typeinfo const&
并提供对 any_cast 函数工作的其他信息访问。