在C ++中对模板参数调用静态函数

用户1056903

以下Java代码printText(text)对泛型参数调用了static方法,该参数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!");
  }

}
亚历克斯

是的,有可能:

template <typename T>
void print(const std::string& text) 
{
    T::printText(text);
}

为了确保它Printer是的基础T,您可以将此编译时检查添加到函数中:

    static_assert(std::is_base_of<Printer, T>::value, "T must inherit from Printer");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章