Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple functions using the same template?

Tags:

c++

templates

Is it possible to include more than one function in the same template instead of rewriting the template twice? Like if you were writing:

template <typename T>
void A() {
    //...
}

template <typename T>
void B() {
    //...
}

Those are not the same function, but they share a similar template (using the generic type T). Is there a way to initialize the template only once?

like image 351
user6245072 Avatar asked Jun 05 '16 12:06

user6245072


People also ask

Can there be more than one arguments to templates?

Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.

Is it possible to overload function templates?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

Can you have templates with two or more generic arguments?

Function Templates with Multiple ParametersYou can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.

What is function template with multiple parameters in C++?

Multiple parameters can be used in both class and function template. Template functions can also be overloaded. We can also use nontype arguments such as built-in or derived data types as template arguments.


1 Answers

Grouping them inside a class template would achieve that.

template <class T>
struct Functions {
    static void A() { /*...*/ }
    static void B() { /*...*/ }
};

However, you lose the ability to deduce T from the functions' arguments, and the calling syntax is longer :

Functions<double>::A();
like image 117
Quentin Avatar answered Nov 01 '22 14:11

Quentin