user6245072
user6245072

Reputation: 2161

Multiple functions using the same template?

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?

Upvotes: 21

Views: 11935

Answers (1)

Quentin
Quentin

Reputation: 63154

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();

Upvotes: 13

Related Questions