【发布时间】:2019-01-15 14:01:33
【问题描述】:
通常在非模板类中,我们将函数声明和定义分开到单独的文件中(.h 和 .cpp)
[1] 但上述做法似乎不适用于模板类。是否建议在单独的文件中编写实现,然后将其包含在 .h 文件的底部?
[2] 以下哪种方案通常建议用于模板类?
[a] 一次性声明和定义或
[b]同一文件中的单独声明和定义
考虑到我们必须注意的复杂语法,如果我们选择 [b]
例如。 [一]
template <typename T>
class unique_ptr final {
private:
T* ptr_;
public:
unique_ptr (T* ptr = nullptr) noexcept {
: ptr_{ ptr } {
}
friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
return lhs.get() == rhs.get();
}
};
[b]
template <typename T>
class unique_ptr final {
private:
T* ptr_;
public:
unique_ptr (T* ptr = nullptr) noexcept;
friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs);
/*** implementations inside the class after all declarations (I am not sure if this makes the code code any easier to understand) ***/
};
/**** Implementations outside the class ***/
/*** Convoluted things needed to make friend functions work ***/
/** like mentioned in : https://stackoverflow.com/questions/3989678/c-template-friend-operator-overloading ***/
【问题讨论】:
-
这是个人喜好和团队编码准则的问题。
标签: c++ c++11 templates compiler-errors