作为
this question的后续:我需要在这样的类函数中做出决定:
template< typename T > bool Class::Fun <T*> ( T& variable ) {...}
T是否是指针.
在上面引用的问题中,答案是使用部分模板专业化.据我所知,这对于类功能是不可能的.这是真的?如果是这样,是否有另一种方法可以找出T是否为指针?
解决方法@H_502_10@
无需专门化成员函数.在那个答案中使用了独立的结构.你仍然可以在类成员函数中使用它.
// 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;
}
};
// 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; } };