最近學到的 template 寫法, template function specification, 可以稍候指明 template 對應某種 class type 時可以用指定的方式進行操作, 這部份比 C# 更複雜也同時更有彈性.
// forward declare
template<class T>
char const * Print_handler(const T* data);
// template function specification
template<>
char const * Print_handler<int>(const int* data) {
auto str = std::to_string(*data);
return str.c_str();
}
template<>
char const * Print_handler<std::string>(const std::string* data) {
return (char*)((*data).c_str());
}
// forward declare
template<class T>
char const * Print_handler(const T* data);
// template function specification
template<>
char const * Print_handler<int>(const int* data) {
auto str = std::to_string(*data);
return str.c_str();
}
template<>
char const * Print_handler<std::string>(const std::string* data) {
return (char*)((*data).c_str());
}
// forward declare template<class T> char const * Print_handler(const T* data); // template function specification template<> char const * Print_handler<int>(const int* data) { auto str = std::to_string(*data); return str.c_str(); } template<> char const * Print_handler<std::string>(const std::string* data) { return (char*)((*data).c_str()); }