如何解决如何使用元组模拟std :: array <15,int&>
很明显,std::array<type,count>
无法存储引用。但是可以写
std::tuple<int &,int &,int &>
获得您的期望。见
#include <array>
#include <tuple>
#include <iostream>
int main(){
int a = 10;
int b = 20;
int c = 20;
// Does not compile
//std::array<int&,3> x = {a,b,c};
using TInt3 = std::tuple<int&,int&,int&>;
TInt3 y = {a,c};
std::cout << sizeof(TInt3) << std::endl;
std::get<0>(y)=11;
std::cout << "a " << a << std::endl;
}
其中输出a 11
。然而,将它写出来很麻烦。如何生成类型(在c ++ 11中)
TupleAllSame<type,count>
以使以下内容等效
TupleAllSame<int &,2> <--> std::tuple<int &,int &>
TupleAllSame<double,4> <--> std::tuple<double,double,double>
TupleAllSame<std::string &,3> <--> std::tuple<std::string &,std::string &,std::string &>
解决方法
基于C++11 implementation of std::index_sequence
(我塞入std14
名称空间中):
namespace impl {
template <class T,class Idx>
struct TupleAllSame;
template <class T,std::size_t... Idx>
struct TupleAllSame<T,std14::index_sequence<Idx...>> {
template <class U,std::size_t>
using depend = U;
using type = std::tuple<depend<T,Idx>...>;
};
}
template <class T,std::size_t Size>
using TupleAllSame = typename impl::TupleAllSame<T,typename std14::make_index_sequence<Size>::type>::type;
,
std::reference_wrapper
可用作数组的元素。语法有时会有些复杂,但是它可以起作用:
#include <functional>
#include <array>
#include <iostream>
int main(){
int a = 10;
int b = 20;
int c = 20;
using rint = std::reference_wrapper<int>;
std::array<rint,3> x = {a,b,c};
std::cout << "a " << a << std::endl;
x[0].get()=11;
std::cout << "a " << a << std::endl;
}
,
基于递归(Wandbox Live)的没有index_sequence的解决方案
#include<iostream>
#include <tuple>
using namespace std;
template <int N,typename T,typename SeqWithArgs>
struct append;
template <int N,template <typename...> class Seq,typename... Args >
struct append<N,T,Seq<Args...> >
{
using type = typename append<N - 1,Seq<T,Args...> >::type;
};
template <typename T,template<typename...> class Seq,typename... Args>
struct append<0,Seq<Args...> >
{
using type = Seq<Args...>;
};
template <typename T,size_t Size>
using TupleAllSame = typename append<Size,std::tuple<> >::type;
int main()
{
int a = 0,b = 1,c = 2;
TupleAllSame<int&,3> t = { a,c };
get<0>(t) = 10;
cout << "a = " << a << endl;
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。