Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在编译时替换元组元素?_C++_Templates_Stl_C++11 - Fatal编程技术网

C++ 如何在编译时替换元组元素?

C++ 如何在编译时替换元组元素?,c++,templates,stl,c++11,C++,Templates,Stl,C++11,有没有办法在编译时替换元组元素 比如说, using a_t = std::tuple<std::string,unsigned>; // start with some n-tuple using b_t = element_replace<a_t,1,double>; // std::tuple<std::string,double> using c_t = element_replace<b_t,0,char>; //

有没有办法在编译时替换元组元素

比如说,

using a_t = std::tuple<std::string,unsigned>;  // start with some n-tuple
using b_t = element_replace<a_t,1,double>;     // std::tuple<std::string,double>
using c_t = element_replace<b_t,0,char>;       // std::tuple<char,double>
使用std::tuple;//从一些n元组开始
使用b_t=element_replace;//std::tuple
使用c_t=元素替换;//std::tuple

查看boost MPL
transform
replace
algos

您可以使用访问元组类型元素的类型。这实际上不允许您替换元组元素类型,但允许您根据在其他元组类型中用作元素类型的类型定义元组类型。

您可以使用以下方法:

// the usual helpers (BTW: I wish these would be standardized!!)
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;
};

// and now we use them
template< typename Tuple, std::size_t N, typename T,
          typename Indices = typename make_indices< std::tuple_size< Tuple >::value >::type >
struct element_replace;

template< typename... Ts, std::size_t N, typename T, std::size_t... Ns >
struct element_replace< std::tuple< Ts... >, N, T, indices< Ns... > >
{
    typedef std::tuple< typename std::conditional< Ns == N, T, Ts >::type... > type;
};
//通常的助手(顺便说一句:我希望这些都是标准化的!!)
模板<标准::大小\u t。。。Ns>
结构索引
{
typedef索引next;
};
模板
结构生成索引
{
typedef typename生成索引::type::next type;
};
模板
结构生成索引<0>
{
类型定义索引类型;
};
//现在我们使用它们
模板::value>::type>
结构元素替换;
模板<类型名。。。Ts,std::size\u t N,typename t,std::size\u t。。。Ns>
结构元素\u替换,N、 T,指数>
{
typedef std::tuple::type…>type;
};
然后像这样使用它:

using a_t = std::tuple<std::string,unsigned>;     // start with some n-tuple
using b_t = element_replace<a_t,1,double>::type;  // std::tuple<std::string,double>
using c_t = element_replace<b_t,0,char>::type;    // std::tuple<char,double>
使用std::tuple;//从一些n元组开始
使用b_t=element_replace::type;//std::tuple
使用c\u t=element\u replace::type;//std::tuple

一个好建议。。。它也严重缺乏肉类。只有链接的答案是不受欢迎的,请不要发布这样的内容。+1-只是一个小的更正:我想你需要
std::Tuple_size
中的
Tuple
?@kfmfe04:D'oh!当然,在我的测试代码中有它,但忘了编辑。现在修好了!