不。不使用 boost::any 也不使用 boost::variant (不符合您的“不枚举所有可能支持 operator+ 的可能类型”的要求)。
你需要做的是自己做。boost::any 背后的概念非常简单。如果您查看文档,他们有一个链接到解释该技术的文章(它基本上是具有多态性的句柄/主体习语)。您需要做的就是确定各种对象必须具有的接口并编写“任何”接口并相应地实现。类似于这样的东西:
struct my_any
{
template < typename T >
my_any(T const& t) : pimpl(new impl<T>(t)) {}
...
some_type get_some_type() const;
...
private:
struct impl_base
{
....
virtual some_type get_some_type() const = 0;
};
template < typename T >
struct impl : impl_base
{
some_type get_some_type() const { return t.get_some_type(); }
impl(T const& t_var) : t(t_var) {}
....
};
boost::scoped_ptr<impl_base> pimpl;
};
some_type operator+ (my_any const& a, my_any const& b)
{
return a.get_some_type() + b.get_some_type();
}
很难想象 operator+ 会对泛型类型做什么,所以我编造了一些对我来说意义不大的东西。你当然需要改变你的需求。