【问题标题】:Calling a static function on a template parameter in C++在 C++ 中对模板参数调用静态函数
【发布时间】:2016-12-30 08:18:23
【问题描述】:

以下 Java 代码在泛型参数 T 上调用静态方法 printText(text),该参数表示 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!");
  }

}

【问题讨论】:

    标签: java c++ templates generics static


    【解决方案1】:

    是的,有可能:

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

    要确保PrinterT 的基础,您可以将此编译时检查添加到函数中:

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

    【讨论】:

    【解决方案2】:

    你可以这样做

    struct A
    {
        static void printMe()
        {
            std::cout << "A print \n";
        }
    };
    
    struct B
    {
        static void printMe()
        {
            std::cout << "B print \n";
        }
    };
    
    
    template<typename T> void printer()
    {
        T::printMe();
    }
    
    int main() {
    
        printer<A>();
        printer<B>();
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多