所以我有以下的情况下,从长远例如道歉,但应正确编译:在编译时是否可以检测到以下分配?
#include <tuple>
#include <functional>
#include <iostream>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/vector.hpp>
namespace mpl = boost::mpl;
namespace aux
{
template <typename ...Args>
struct to_vector
{ };
template <typename T, typename ...Args>
struct to_vector<T, Args...>
{ typedef typename mpl::push_front<typename to_vector<Args...>::type, T>::type type; };
template <typename T>
struct to_vector<T>
{ typedef typename mpl::vector<T> type; };
template <>
struct to_vector<>
{ typedef typename mpl::vector<> type; };
template <typename Dest, typename T>
struct tuple_adder
{
typedef decltype(std::tuple_cat(std::declval<Dest>(), std::make_tuple(std::declval<T>()))) type;
};
}
struct foo
{
struct storage
{ };
template <typename T>
struct placeholder : storage
{
placeholder(T&& t) : content(t)
{ }
T content;
};
storage* data;
template <typename ...Args>
foo(Args&&... args)
: data()
{
typedef typename mpl::fold<
typename aux::to_vector<Args...>::type,
std::tuple<>,
aux::tuple_adder<mpl::_1, mpl::_2>
>::type tuple_type;
// Instantiate the tuple
data = new placeholder<tuple_type>(std::make_tuple(std::forward<Args>(args)...));
}
template <typename ...Args>
void set(Args&&... args)
{
typedef typename mpl::fold<
typename aux::to_vector<Args...>::type,
std::tuple<>,
aux::tuple_adder<mpl::_1, mpl::_2>
>::type tuple_type;
auto tp = static_cast<placeholder<tuple_type>*>(data);
*tp = std::make_tuple(std::forward<Args>(args)...);
}
};
int main()
{
foo f(1, 2., std::string("Hello"));
f.set(4, 3., std::string("Bar"));
f.set(3., std::string("Bar"), 3.);
}
的想法很简单,foo
利用类型擦除来存储通过构造构建的tuple
。随后的限制应该是set
是唯一允许在从一个可变参数列表中产生的tuple
所保持的元组匹配(已不幸得了它的类型删除。)
现在我可以然而,在使用typeid()
运行时检测出,我我想知道在编译时是否有一种方法可以进行相同的检测。唯一的限制是foo
不能作为模板,并variant
超出我想允许foo
与必要的字段来构建(在编译时所有指定...)
恐怕答案是,这是不可能的(由于类型擦除),但我希望的方式来实现这一功能的一些想法......
你要知道,如果你可以存储在MATC ......不,先生运行时值编译时检测。 – 2013-03-01 11:59:33
您只能在运行时检查它,但你并不需要'typeid'为,只是'dynamic_cast' – 2013-03-01 12:12:33
更换'static_cast' @ R.MartinhoFernandes,我不感兴趣,在运行时间值,我只想检查类型。上面的例子稍微有些复杂(通过'mpl :: vector'来生成元组的步骤在那里,因为我有一个过滤器函数来移除我不想要的类型)。结果,'set()'只能接受已过滤的*类型* ... – Nim 2013-03-01 12:21:49