use*_*903 6 c++ java generics static templates
以下Java代码printText(text)在泛型参数上调用静态方法,该参数T表示派生类Printer.是否有可能在C++中实现完全相同的行为?如果有,怎么样?
public class Printer {
public static void printText(String text) {
System.out.println(text);
}
public static <T extends Printer>void print(String text) {
T.printText(text);
}
public static void main(String[] args) {
Printer.print("Hello World!");
}
}
Run Code Online (Sandbox Code Playgroud)
对的,这是可能的:
template <typename T>
void print(const std::string& text)
{
T::printText(text);
}
Run Code Online (Sandbox Code Playgroud)
要确保它Printer是一个基础T,您可以将此编译时检查添加到该函数:
static_assert(std::is_base_of<Printer, T>::value, "T must inherit from Printer");
Run Code Online (Sandbox Code Playgroud)