有没有办法专门化模板函数来区分参数类型何时是指针,何时不是?
Is there a way to specialize a templated function to discriminate when the type of an argument is a pointer from when it is not?
让我们考虑一下那些模板化函数
template <typename T> void Func(T* p)
{
printf("pointer ");
Func(*p);
}
template <typename T> void Func(T)
{
printf("type");
}
我想这样写,如果我给一个带有多个指针类型的参数,专门针对指针类型的函数被递归调用到不再有指针的地方,最后没有指针的函数是叫。
通常,如果我写
int a;
int* a2 = &a;
int** a3 = &a2;
int*** a4 = &a3;
Func(a4);
我要输出写
pointer pointer pointer type
不幸的是,如果我那样写,我得到的只是对非指针函数的调用。
有什么办法可以实现吗?
您只需要调换功能即可。在 template <typename T> void Func(T* p)
中,当您执行 Func(*p);
时,编译器只知道 template <typename T> void Func(T* p)
。所以你最终递归地调用同一个函数,直到它在你不再有指针时出错。如果你使用
template <typename T> void Func(T)
{
printf("type");
}
template <typename T> void Func(T* p)
{
printf("pointer ");
Func(*p);
}
然后当你调用 Func(*p);
时,编译器知道 template <typename T> void Func(T)
并且当你不再有指针给你时会调用
pointer pointer pointer type
让我们考虑一下那些模板化函数
template <typename T> void Func(T* p)
{
printf("pointer ");
Func(*p);
}
template <typename T> void Func(T)
{
printf("type");
}
我想这样写,如果我给一个带有多个指针类型的参数,专门针对指针类型的函数被递归调用到不再有指针的地方,最后没有指针的函数是叫。 通常,如果我写
int a;
int* a2 = &a;
int** a3 = &a2;
int*** a4 = &a3;
Func(a4);
我要输出写
pointer pointer pointer type
不幸的是,如果我那样写,我得到的只是对非指针函数的调用。
有什么办法可以实现吗?
您只需要调换功能即可。在 template <typename T> void Func(T* p)
中,当您执行 Func(*p);
时,编译器只知道 template <typename T> void Func(T* p)
。所以你最终递归地调用同一个函数,直到它在你不再有指针时出错。如果你使用
template <typename T> void Func(T)
{
printf("type");
}
template <typename T> void Func(T* p)
{
printf("pointer ");
Func(*p);
}
然后当你调用 Func(*p);
时,编译器知道 template <typename T> void Func(T)
并且当你不再有指针给你时会调用
pointer pointer pointer type