简体   繁体   中英

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 . Is it possible to achieve exactly the same behaviour in 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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