简体   繁体   English

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

[英]Calling a static function on a template parameter in C++

The following Java code calls the static method printText(text) on the generics parameter T which represents a derived class of Printer . 以下Java代码在泛型参数T上调用静态方法printText(text) ,该参数表示Printer的派生类。 Is it possible to achieve exactly the same behaviour in C++? 是否有可能在C ++中实现完全相同的行为? If yes, how? 如果有,怎么样?

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!");
  }

}

Yes, it is possible: 对的,这是可能的:

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

To make sure that Printer is a base of T , you can add this compile-time check to the function: 要确保PrinterT的基础,可以将此编译时检查添加到函数中:

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

You can do this 你可以这样做

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM