Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading template class with template function

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?

like image 756
αλεχολυτ Avatar asked Sep 26 '17 20:09

αλεχολυτ


People also ask

Can you overload a template function?

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.

What is the relationship between function templates and overloading?

overloading is used when we have various functions , doing SIMILAR operations . template is used when we have various functions , doing IDENTICAL operations .

Is class template and function template the same?

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.

Can we have overloading of the function templates clear response?

Explanation: Template function cannot be overloaded as done in this program.


1 Answers

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.

like image 107
n. 1.8e9-where's-my-share m. Avatar answered Nov 09 '22 19:11

n. 1.8e9-where's-my-share m.