作为 this question 的后续行动: 我需要在这样的类函数中做出决定:
template< typename T > bool Class::Fun <T*> ( T& variable ) {...}
T是否为指针
在上面引用的问题中,答案是使用部分模板特化。据我所知,这对于类函数是不可能的。这是真的?如果是这样,是否有另一种方法可以确定 T 是否为指针?
最佳答案
无需特化成员函数。在该答案中使用了独立结构。您仍然可以在类成员函数中自由使用它。
// stand-alone helper struct
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = true; };
// your class
class Class{
public:
template<typename T>
void Fun(T& variable) {
std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}
};
另一方面,您可以重载函数:
class Class {
public:
template<typename T>
void Fun(T& variable) {
std::cout << "is it not a pointer! " << std::endl;
}
template<typename T>
void Fun(T*& variable) {
std::cout << "is it a pointer! " << std::endl;
}
};
关于c++ - 模板类函数 T : How to find out if T is a pointer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1412737/