一部の C++11 では:
// sequence creation code from: http://stackoverflow.com/a/13315884/420683
template<unsigned... Is>
struct seq{};
template<unsigned N, unsigned... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
#include <string>
struct Pod{
char str[16];
};
template < unsigned... Is >
Pod create_pod(std::string const& p, seq<Is...>)
{
if(p.size() >= sizeof...(Is))
{
return {p[Is]..., '\0'}; // if it has to be 0-terminated
}else
{
// quick fix, there are better ways though
char t[sizeof...(Is) +1];
std::copy(p.begin(), p.end(), std::begin(t));
t[p.size()] = '\0';
return {t[Is]...};
}
}
Pod create_pod(std::string const& p)
{
return create_pod( p, gen_seq<sizeof(Pod::str) -1 >{} );
}
int main() {
std::string s("does not compile");
Pod pod = create_pod(s);
}
または、再帰を使用します (テストされていません!):
template < unsigned... Is >
Pod create_pod(std::string const& p, seq<Is...>, seq<>)
{
return {p[Is...], '\0'};
}
template < unsigned... Is, unsigned... Is0 >
Pod create_pod(std::string const& p, seq<Is...>, seq<Is0...>)
{
if(sizeof(Pod::str) > sizeof...(Is) && p.size() > sizeof...(Is))
{
create_pod(p, gen_seq<sizeof...(Is)+1>{}, gen_seq<sizeof...(Is0)-1>{});
}else
{
return {p[Is]..., 0*Is0..., '\0'};
}
}
Pod create_pod(std::string const& p)
{
return create_pod( p, gen_seq<0>{},
gen_seq<sizeof(Pod::str) -1 >{} );
}