简体   繁体   中英

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?

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.

I think function template name is allowed to be the same as something else to allow overloading, while class template name is explicitly disallowed to match something else according to

14 Templates [temp]

  1. A class template shall not have the same name as any other template, class, function, variable, enumeration, enumerator, namespace, or type in the same scope (3.3), except as specified in (14.5.5).

[update] the rest of this piece makes me think that the case with function template not causing the same error violates the standard requirements:

Except that a function template can be overloaded either by non-template functions (8.3.5) with the same name or by other function templates with the same name (14.8.3), a template name declared in namespace scope or in class scope shall be unique in that scope .

and VS / clang / gcc seem to disagree on it godbolt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM