2013-04-27 56 views
1

我正在使用BSD文件描述符读取和和管道(与readwrite电话)写值的代码。这是一个简单的IPC系统的一部分,其中一个进程告诉另一个进程运行并返回结果。大多数情况下,只有一个返回值,但是一些过程需要返回多个返回值。为了避免为每个人都做一个新的struct,我想我可以使用std::tuple s。如何将一个可变数量的值读入std :: tuple?

不过,我只有很少的成功创建读元素融入一个元组的一般方法。我试图单独读取这些值,因为这两个进程没有相同的位数(一个是64位,另一个是32位),我担心tuple结构中的不同对齐要求会导致它们不兼容。这是我的尝试:

template<typename TTupleType> 
struct TupleReader 
{ 
    int fd; 
    TTupleType& storage; 

    TupleReader(int fd, TTupleType& storage) : fd(fd), storage(storage) 
    { } 

    template<size_t Index = std::tuple_size<TTupleType>::value - 1> 
    inline void Read() 
    { 
     Read<Index - 1>(fd); 
     auto& ref = std::get<Index>(storage); 
     ::read(fd, &ref, sizeof ref); 
    } 
}; 

这显然不能编译,因为它试图实例Read<-1>和STL的实现我用渔获std::get<-1>static_assert。但是,在类范围中专门化模板化函数是非法的,但由于父项struct也是模板化的,因此无法将方法专门化到其他范围之外。 template<typename TTupleReader> void TupleReader<TTupleType>::Read<0>()被认为是部分专业化。

所以看起来我被这种方法陷入了僵局。有没有人看到一种方法来做到这一点?

回答

4

你可以尝试使用索引:

template< std::size_t... Ns > 
struct indices 
{ 
    typedef indices< Ns..., sizeof...(Ns) > next; 
}; 

template< std::size_t N > 
struct make_indices 
{ 
    typedef typename make_indices< N - 1 >::type::next type; 
}; 

template<> 
struct make_indices<0> 
{ 
    typedef indices<> type; 
}; 

struct sink 
{ 
    template<typename... T> 
    sink(T&&...) {} 
}; 

template<typename TTupleType> 
struct TupleReader 
{ 
    int fd; 
    TTupleType& storage; 

    TupleReader(int fd, TTupleType& storage) : fd(fd), storage(storage) 
    { } 

    template<size_t... Ns> 
    inline void ReadImpl(const indices<Ns...>&) 
    { 
     sink { ::read(fd, &std::get<Ns>(storage), 
          sizeof(typename std::tuple_element<Ns,TTupleType>::type))... }; 
    } 

    inline void Read() 
    { 
     ReadImpl(typename make_indices<std::tuple_size<TTupleType>::value>::type()); 
    } 
}; 
+0

很聪明。我会尝试的。 – zneak 2013-04-27 14:47:56

0

您可以创建一个内部模板类TupleReader::Reader<i>包含单个静态函数Read。然后,您可以根据需要部分专门化该内部类的<i=0>大小写。然后TupleReader::Read<n>可以实例化TupleReader::Reader<n>并调用静态函数TupleReader::Reader<n>::Read

相关问题