2013-03-01 64 views
2

所以我有以下的情况下,从长远例如道歉,但应正确编译:在编译时是否可以检测到以下分配?

#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与必要的字段来构建(在编译时所有指定...)

恐怕答案是,这是不可能的(由于类型擦除),但我希望的方式来实现这一功能的一些想法......

+1

你要知道,如果你可以存储在MATC ......不,先生运行时值编译时检测。 – 2013-03-01 11:59:33

+0

您只能在运行时检查它,但你并不需要'typeid'为,只是'dynamic_cast' – 2013-03-01 12:12:33

+0

更换'static_cast' @ R.MartinhoFernandes,我不感兴趣,在运行时间值,我只想检查类型。上面的例子稍微有些复杂(通过'mpl :: vector'来生成元组的步骤在那里,因为我有一个过滤器函数来移除我不想要的类型)。结果,'set()'只能接受已过滤的*类型* ... – Nim 2013-03-01 12:21:49

回答

3

编译时类型系统的一点是,它限制了对价值所允许的操作类型。如果两个对象是相同的类型,那么他们承认相同的允许操作。

因此,没有,有没有办法让编译器知道你想要什么允许的,因为你已经删除的区别。

+0

只要使用类型擦除,我无法找到运行时检查的方式,所以我想删除这个问题,但你已经回答了(无论如何是正确的答案),所以我会接受这一点,并离开原来的繁荣。 – Nim 2013-03-01 15:16:33

相关问题