Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 270
user1056903 Avatar asked Aug 23 '16 13:08

user1056903


People also ask

Can a static function be template?

The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .

What happens when there is static member in a template class function?

The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member.

Can we pass Nontype parameters to templates?

Template non-type arguments in C++ It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.

Can function parameter template?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


2 Answers

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");
like image 165
alexc Avatar answered Oct 05 '22 02:10

alexc


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;
}
like image 25
parapura rajkumar Avatar answered Oct 04 '22 02:10

parapura rajkumar