Getting confused with C++ template - c++

I am looking at some c++ code and do not understand the purpose of the template declaration in this situation:
template<> void operator>>(const ClassA& s, const ClassB d) {...}
What is the semantic of template<>?

This is, indeed, template specialization, as others before mentioned. There must be some previously declared function template, such as:
template<typename T, typename U>
void operator>>(const T& s, const U d) {...}
However, it is quite misguided. It is much better to remove the template<> altogether, so operator>> would just be overloaded. The problem with function template specialization is that it may lead to unexpected behaviour in the presence of overloaded functions (and operator>> has lots of overloads), since the specialization does not overload. This means that the compiler first selects the most appropriate overload for the function and then, if the selected overload is a function template, it looks for template specializations to see if there is an appropriate one.
A classical example (unfortunately, I don't remember where I read it). Consider this overloaded function template:
template <typename T>
void Function(T param);
template <typename T>
void Function(T* param);
template <>
void Function(int* param);
main()
{
int i = 5;
Function(&i);
}
As expected, the template specialization for int* is called. But just change the order of the function definitions:
template <typename T>
void Function(T param);
template <>
void Function(int* param);
template <typename T>
void Function(T* param);
main()
{
int i = 5;
Function(&i);
}
Now the general template for T* is called, since we are specializing the template for T, not for T*, and this second template is better suited for our call. This would be avoided if we overloaded the function instead of specializing the template:
void Function(int* param);
Now the order of declaration does not matter, we will always call the overload for int*.
UPDATE: Now I know who to credit. I read about this in an article by Herb Sutter. The example was provided by Peter Dimov and Dave Abrahams.

This is Template specialization

You use this syntax when you want to provide a special handler for a particular template type. Consider:
// A normal template definition.
template <typename AType>
whoami () { std::cout << "I am an unknown type."; }
// Now we specialize.
template <>
whoami<int> () { std::cout << "I am an integer!"; }
There's some other nonsense involved, particularly "partial specialization", but that's the basic function of template <>.

It is a template specialization: (fully or partially) resolving the template for a specific type. (Your particular example seems to be a full specialization, as no more template parameters are left unresolved in it. If the template has multiple parameters, and you specialize only some of them, it is called partial template specialization)
This allows one to provide type-specific optimizations for a given template, or to do many clever tricks such as detecting the static type of variables etc.

Related

Empty angle-brackets after a function's name in explicit specialization

Here is a code from the article Why not specialize function templates?
template<class T>
void f(T); // (1)
template<class T>
void f(T*); // (2)
template<>
void f<>(int*); // (3)
My question is about the last declaration. What does that syntax mean? When we want to fully specialize a function template, e.g. (1), for some type we usually write:
template<>
void f<int>(int);
i.e. we put that type into the angle-brackets after the function' name.
So what does the syntax (3) means?
In your case,
template<> void f<>(int*);
is an explicit specialization of
template<class T> void f(T*);
base template. It's the same as
template<> void f<int>(int*);
just the template argument is deduced.
You can even write:
template<> void f(int*);
with the same effect. A similar case is presented on cppreference, see section Explicit specializations of function templates, where there is written:
When specializing a function template, its template arguments can be omitted if template argument deduction can provide them from the function arguments.
The relevant part of the C++ Standard: http://eel.is/c++draft/temp.expl.spec#11.
A missing template argument will be deduced by the compiler if you don't provide it. In this particular case it will be deduced to int* because the second template is more specialized (but both are the candidates). So
template<> void f<>(int*)
will become
template<> void f<int>(int*)
after type deduction.

C++ explicit specialization of member template belonging to template class

In the current C++ standard draft, there is this example in this paragraph belonging to the section related to explicit specialization of templates:
template<class T> struct A {
void f(T);
template<class X1> void g1(T, X1);
template<class X2> void g2(T, X2);
void h(T) { }
};
// specialization
template<> void A<int>::f(int);
// out of class member template definition
template<class T> template<class X1> void A<T>::g1(T, X1) { }
// member template specialization
template<> template<class X1> void A<int>::g1(int, X1); //(1)
// member template specialization
template<> template<>
void A<int>::g1(int, char); //(2)
In (1) it seems more like g1 was specialized to be still a function template in the specialized version of A (A< int >), while in (2) it seems like g1 is itself specialized for its own set template parameters ( (int, from A< int >), char).
I find there to be a difference between these specializations (again, (1) feels like declaring a new version of g1 to be used for a "special version" of its "container" A, while (2) feels like a specialization regarding g1 itself (or regarding its own template parameters).
Furthermore, consider this example:
template<class T> struct A{
int f() { return 1; }
}
template<>
int A<int>::f() { return 2; } //(3)
To me (1) and (3) are the same "kind of specialization", one that is linked to a special version of the "container", while (2) is a specialization of the entity (template) itself.
Does the standard mention this difference or are these two kinds of specialization referred to as the same?
Thank you.
First, your #3 is equivalent to the first specialization in the cited example, except that the standard’s f uses the class’s template parameter in its signature—presumably to illustrate that, since the signature must match for a specialization, template arguments for the class may need to be repeated in the specialization declaration.
Then, the difference is that #1 is a specialization of a member of A<T> when T is int—a sort of shorthand for writing a specialization of A<int> itself that is mostly the same as the primary template. In particular, to avoid being misleading, the signature for the member being specialized must be unchanged from the (instantiation of the) primary template. In this case, that means it’s still a template.
On the other hand, #2 is a specialization of a template that happens to be a member of A<int>—the specialization is of A<int>::g1 itself, not of “A<T>::g1 when T is int” as for #1. This of course applies only when the member is a template, unlike #3. (In this case, #2 is a specialization of the very template declared by #1!)
Part of the point of [temp.expl.spec]/15 is that these two cases are not strongly distinguished syntactically. The difference is largely academic: both are surgical changes to a templated entity for certain arguments.

Function templates: extern template vs explicit specialisation

Consider the following function template declaration:
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);
There is only one possible valid instantiation of this template, namely with T = int. I'd like to put this definition in an implementation file. I can think of two possible ways of doing so. (If you're wondering why on earth I'd do this rather than just saying void foo(int i), it's because the template version prevents implicit conversions at the call site.)
Approach 1:
I can use an extern template declaration to tell other TUs that foo<int>() is instantiated elsewhere:
// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);
extern template void foo(int);
// In foo.cpp
template <typename T, typename>
void foo(T i) { ... } // full template definition
template void foo(int); // explicit instantiation with T = int
Approach 2:
I can provide an explicit specialisation for the int case:
// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);
template <> void foo(int i); // explicit specialisation declaration (*)
// In foo.cpp
template <>
void foo(int i) { ... } // explicit specialisation definition
Questions:
Are both of these approaches legal, or am I unintentionally relying on UB?
If both are legal, is there a good reason to prefer one approach over the other, other than the fact that approach 2 is very slightly less typing? Both GCC and Clang work equally well with either approach.
For approach 2, is the explicit specialisation declaration at (*) actually required? Again, both GCC and Clang are perfectly happy if it's omitted, but doing so makes me uncomfortable about the fact that a call to foo(3) in another TU is an implicit instantiation of a template with no definition visible, and no promise that such a definition exists elsewhere.
There is a third approach. In approach 3 you specify the function you want to have and the you add a template overload and mark that as delete. That looks like
void foo(int i)
{
// stuff
}
template <typename T>
void foo(T t) = delete;
Since the template version will match all types exactly it will be preferred in all cases except int since a non template exact match is preferred to a template one. So you will only be able to call foo with an int and all other types will give you an error that they are trying to call the deleted function void foo(T t).
Live Example

The meaning of template keyword in the function declaration

What has the meaning the "using of template keyword in the function declaration"?
In this example compiler errors with error: "func" is not a template function.
template<typename T>
struct Window {
T value;
};
template void func(Window<int>, int);
template<typename T>
void func(Window<T>, T) {
}
int main(void) {
}
But below example is ok.
template<typename T>
struct Window {
T value;
};
template<typename T>
void func(Window<T>, T) {
}
template void func(Window<int>, int);
int main(void) {
}
What is the meaning with "template" in the above case?
Is it just indicator that this function is template function?
A declaration that begins with the keyword template and does not have the <pointy braces> immediately afterward is called an explicit instantiation. It means to look up the template definition and plug in the specified template parameters to get a specific function specialization or class specialization. So in the first example, the compiler is complaining it can't instantiate func(Window<int>, int) because it doesn't yet know anything about a template called func.
Explicit instantiations are usually not necessary, since templates can be implicitly instantiated just by attempting to use them. But explicit instantiation gives some control over where and how related linker symbols appear, and can in some cases be used to move a template definition out of a header file into a source file.
This is just because in your first example you have the definition of the template
template<typename T>
void func(Window<T>, T) {
}
after the forced instantiation that's represented by this line:
template void func(Window<int>, int);
Whereas in the second example they're the right way around.
But the comment to your question is fair, you are asking a basic question ('what does template mean'), which is best answered by a thoroughgoing study of the subject.

What is the rationale behind the syntax chosen to declare template friends?

Declaring template function friends involves some incredibly unintuitive syntax, even for C++! What is the rationale behind the choice of syntax for the extra <> needed? Wouldn't it make more sense to use the template keyword?
For those that don't know about this, here is an example of what you might try to do:
template <typename T>
class Foo
{
int x;
friend void bar(Foo<T>);
};
template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}
If you try to call bar(Foo<T>()), you will get linker errors.
To solve this, you have to forward declare bar (and therefore Foo) and then stick an oddly placed <> in the friend declaration.
template <typename T> class Foo;
template <typename T> void bar(Foo<T>);
template <typename T>
class Foo
{
int x;
friend void bar<>(Foo<T>); // note the <> (!?)
};
template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}
My question is, what is the rationale behind the <> syntax? Wouldn't it be more intuitive to use the template keyword or something along those lines?
EDIT: To clarify, I already know why the <> is required, what I want to know is why they chose to use <> to disambiguate it instead of some other more intuitive syntax.
Wait. You are not declare a friend template. You declare a specialization of a template as friend! As such, why would you want to put a template clause there?
The syntax to name specializations of function templates is by teplateName<ArgumentList>, and that is what you shall use according to the Standard in the friend declarations.
If you want to befriend the whole template and all specializations generated and explicitly specialized, you can still do that, and then you can use a template clause
template<typename U>
friend void bar(Foo<U>);
Quoting this page:
The non-template function is called because a non-template function takes precedence in overload resolution.
So my guess the friend void bar<>(Foo<T>); is intuitive because you want to make sure it's the template function you are calling and not an overload for Foo<T>. There would otherwise no way for the compiler to notice if the templated or the non-templated function is the class'es friend.
Why the <> syntax is used and not the template syntax is not clear to me.