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!");
}
}
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> .
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With