编写专门化在语法上是非法的时如何删除成员函数(完整)专门化?
How to delete a member function (full) specialization when writing that specialization is syntactically illegal?
我正在写一个指针 class 并且很自然地将取消引用运算符定义为一个成员函数。但是,如果此类型现在为 void,我需要删除该函数,因为您不能取消引用 void 指针。但是写出那个专业化本身就是一个语法错误:
// in ptr.h
template<typename T>
class ptr {
public:
T& operator * () const;
};
//in ptr.cpp
template<>
void& ptr<void>::operator * () const = delete;
那么我该如何实现呢?要修复语法错误,我必须犯语法错误?
我已经尝试查看 std::unique_ptr class 的源代码,但我真的无法理解该代码 tbh
您不能像您尝试的那样在头文件和 cpp 文件之间分离模板的声明和实现:
Why can templates only be implemented in the header file?
无论如何,您不能只特化模板的一种方法class。您必须专门化整个模板,例如:
template<typename T>
class ptr {
public:
T& operator * () const;
};
template<>
class ptr<void> {
public:
// simply omit operator* altogether, since void& is illegal...
//void& operator * () const = delete;
};
否则可以使用SFINAE省略T=void
时的运算符,eg:
#include <type_traits>
template<typename T>
class ptr {
public:
template<typename U = T>
typename
std::enable_if<!std::is_same<U, void>::value, U&>::type
operator * () const;
};
我正在写一个指针 class 并且很自然地将取消引用运算符定义为一个成员函数。但是,如果此类型现在为 void,我需要删除该函数,因为您不能取消引用 void 指针。但是写出那个专业化本身就是一个语法错误:
// in ptr.h
template<typename T>
class ptr {
public:
T& operator * () const;
};
//in ptr.cpp
template<>
void& ptr<void>::operator * () const = delete;
那么我该如何实现呢?要修复语法错误,我必须犯语法错误?
我已经尝试查看 std::unique_ptr class 的源代码,但我真的无法理解该代码 tbh
您不能像您尝试的那样在头文件和 cpp 文件之间分离模板的声明和实现:
Why can templates only be implemented in the header file?
无论如何,您不能只特化模板的一种方法class。您必须专门化整个模板,例如:
template<typename T>
class ptr {
public:
T& operator * () const;
};
template<>
class ptr<void> {
public:
// simply omit operator* altogether, since void& is illegal...
//void& operator * () const = delete;
};
否则可以使用SFINAE省略T=void
时的运算符,eg:
#include <type_traits>
template<typename T>
class ptr {
public:
template<typename U = T>
typename
std::enable_if<!std::is_same<U, void>::value, U&>::type
operator * () const;
};