Yaniv G
Yaniv G

Reputation: 366

C++ Template Specialization Concept

I'm exploring C++ Template Specialization, and I'm trying to understand the syntax rules:

template <typename T> T foo(T a, char b) {
   /* some code */
}

template <> _X foo<_Y>(_Z a, _W b) {
   /* some code */
}

take as an example my simple example with the _X, _Y, _Z, _W as type placeholders. It seems to me that if I specified the types _Z and _W, why do I need the _Y inside the <_Y>? and does _Y has to be identical to _Z or _W types?

Regardless of the implementation - I'm trying to understand every tutorial in this topic but it is never explained properly (or maybe it's just me :) ) - If I already defined a specialized template for certain types, why isn't it enough to call the template function with those types? why do I need to have the _Y type?

why do I need to call the specialized template like this: foo<_Y>(c, d) and why foo(c, d) is not enough?

Also, from all the testing I have been doing it seems that all types: _X, _Y, _Z, _W must be identical otherwise I get a build error. Is that really the case?

I hope it makes sense.

Upvotes: 0

Views: 96

Answers (1)

user17732522
user17732522

Reputation: 76879

You don't need to. As long as the template arguments can be deduced as in a function call, you can leave out an explicit template argument list.

For example

template <> int foo(int a, char b) {
   /* some code */
}

works as explicit specialization of foo<int>, because the argument for T in the primary template can be deduced to int from the first function parameter in the specialization, the same way it would be if you made a function call foo(0, '0') (type of 0 is int and type of '0' is char), where you also don't have to write foo<int>(0, '0') explicitly.

However, in order to match the primary template _W must always be char. Similarly _X and _Z (and if given _Y) must all be the same type.

Upvotes: 1

Related Questions