C++ allows to use class and function with the same name in one namespace:
struct S {};
void S() {}
In this case pure name S
means function S
. To use struct instead you need to explicitly add struct
before name.
It's also possible to make function template and still use both of them:
template <class T>
void S() {}
struct S {};
But using template struct is forbidden
void S() {}
template <class T>
struct S {};
and gives error like this:
error: redefinition of 'S' as different kind of symbol
What is the reason for this? Why not to allow use template struct here? Is there any situation where using explicit keyword struct
before S
(like for non-template version) could not solve name collision if it was allowed? Maybe there is proposal exist?
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.
overloading is used when we have various functions , doing SIMILAR operations . template is used when we have various functions , doing IDENTICAL operations .
The class template in c++ is like function templates. They are known as generic templates. They define a family of classes in C++. Here Type is a placeholder type name, which will be specified when a class instantiated.
Explanation: Template function cannot be overloaded as done in this program.
C++ allows to use class and function with the same name in one namespace.
struct S {}; void S() {}
Normally when you declare struct S
, you can refer to the type in two ways: as S
and as struct S
. But that's only until you declare something else named S
, for example, a function. When you do that, the name of the type is not S
any more. It's struct S
only. The name S
is reserved for the function.
This is done for compatibility with C. C code uses this device frequently. Unlike C++, C places struct and union tags in a different name space from normal identifiers, and struct S
cannot be referred to as simply S
.
So C++, in order to be able to compile C code that uses this device, makes an exception for struct tags that are reused as a different kind of identifier.
As class
is nearly synonymous with struct
, this is done for the class
keyword too.
But C has no templates and there's no need to provide backward compatibility for them, so no such exception for class templates is made.
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