use*_*592 3 c++ templates tuples
我正在尝试为元组创建打印方法.我检查了其他人指定的解决方案,都使用了辅助结构.我不想使用helper struct.我觉得以下代码是有效的,但不能直接得到它.
#include <iostream>
#include <tr1/tuple>
template<typename tupletype,size_t i>
void print< tupletype ,0>(tupletype t)//error: expected initializer before ‘<’ token
{
std::cout<<std::tr1::get<0><<" ";
}
template<typename tupletype,size_t i>
void print(tupletype t)
{
std::cout<<std::tr1::get<i><<" ";// no match for 'operator<<' in 'std::cout << get<-78ul>'(my ide actually hangs here!)
print<tupletype,i-1>(t);
}
int main (int argc, char * const argv[]) {
std::tr1::tuple<int,float> a(3,5);
typedef std::tr1::tuple<int,float> tupletype;
print<tupletype,0>(a);
}
Run Code Online (Sandbox Code Playgroud)
Xeo*_*Xeo 14
这是没有特定帮助器结构的一个:
#include <iostream>
#include <tuple>
template<std::size_t> struct int2type{};
template<class Tuple, std::size_t I>
void print_imp(Tuple const& t, int2type<I>){
print_imp(t, int2type<I-1>());
std::cout << ' ' << std::get<I>(t);
}
template<class Tuple>
void print_imp(Tuple const& t, int2type<0>){
std::cout << std::get<0>(t);
}
template<class Tuple>
void print(Tuple const& t){
static std::size_t const size = std::tuple_size<Tuple>::value;
print_imp(t, int2type<size-1>());
}
Run Code Online (Sandbox Code Playgroud)
sbi*_*sbi 13
首先,您需要在专门化之前声明函数模板:
template<typename tupletype,size_t i>
void print(tupletype t);
Run Code Online (Sandbox Code Playgroud)
但是,它仍然无法工作,因为您不能部分专门化功能模板 - 而您要做的是部分专业化.
因此,做你想做的唯一方法就是回到类模板部分特化:
template<typename tupletype,size_t i>
struct printer;
template<typename tupletype>
struct printer< tupletype ,0> {
static void print(tupletype t)
{
std::cout<<std::tr1::get<0>(t)<<" ";
}
};
template<typename tupletype,size_t i>
struct printer {
static void print(tupletype t)
{
std::cout<<std::tr1::get<i>(t)<<" ";
printer<tupletype,i-1>::print(t);
}
};
template<typename tupletype,size_t i>
void print(tupletype t)
{
printer<tupletype,i>::print(t);
}
Run Code Online (Sandbox Code Playgroud)
你为什么不想那样做?
| 归档时间: |
|
| 查看次数: |
6150 次 |
| 最近记录: |