Last active
May 8, 2019 08:21
-
-
Save anonymouss/29267e363d68c24ca78bfd89857c5fe5 to your computer and use it in GitHub Desktop.
Template notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1, 类内声明同时定义 | |
template <typename T> | |
class VectorWrapper { | |
public: | |
VectorWrapper(const std::initializer_list<T> &list) { mVector = list; } | |
friend std::ostream &operator<<(std::ostream &os, const VectorWrapper<T> &vec_w) { | |
vec_w.print_l(os); | |
return os; | |
} | |
private: | |
void print_l(std::ostream &os) const { | |
for (const auto &v : mVector) | |
std::cout << v << ", "; | |
} | |
std::vector<T> mVector; | |
}; | |
// 2, 类内声明,类外定义(使用不同的模板类名,防止冲突隐藏) | |
template <typename T> | |
class VectorWrapper { | |
public: | |
VectorWrapper(const std::initializer_list<T> &list) { mVector = list; } | |
// 声明 | |
template <typename U> | |
friend std::ostream &operator<<(std::ostream &os, const VectorWrapper<U> &vec_w); | |
private: | |
void print_l(std::ostream &os) const { | |
for (const auto &v : mVector) | |
std::cout << v << ", "; | |
} | |
std::vector<T> mVector; | |
}; | |
// 定义 | |
template <typename U> | |
friend std::ostream &operator<<(std::ostream &os, const VectorWrapper<U> &vec_w) { | |
vec_w.print_l(os); | |
return os; | |
} | |
// 3, 类外声明定义,类内实例化(需要前置声明类) | |
template <typename T> | |
class VectorWrapper; // forward declaration for friend function to use | |
// declaration and definition of friend function | |
template <typename T> | |
friend std::ostream &operator<<(std::ostream &os, const VectorWrapper<T> &vec_w) { | |
vec_w.print_l(os); | |
return os; | |
} | |
template <typename T> | |
class VectorWrapper { | |
public: | |
VectorWrapper(const std::initializer_list<T> &list) { mVector = list; } | |
// 为类型 T 实例化 | |
friend std::ostream &operator<<<T>(std::ostream &os, const VectorWrapper<T> &vec_w); | |
private: | |
void print_l(std::ostream &os) const { | |
for (const auto &v : mVector) | |
std::cout << v << ", "; | |
} | |
std::vector<T> mVector; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
struct TestString { | |
T data; | |
TestString(const T &d) : data(d) {} | |
}; | |
TestString(const char *)->TestString<std::string>; // (1). 推导指引,since C++ 17 | |
int main() { | |
// without (1), 无法编译,类型 T 会被推导为 char[6] | |
TestString ts{"hello"}; | |
} | |
/** | |
* 传递数组或字符串字面值给模板时要各位小心,如果模板参数此时定义为引用,那么参数就不会退化(decay)。 | |
* 如 const char[N] 不会隐式转换为 const char * | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment