为什么C ++不允许两个具有相同名称的函数/类模板,只有非类型模板参数(整数类型)的类型不同?

问题描述 投票:12回答:1

我尝试这个时编译器会出错。我试过VC ++和g ++。

这同样适用于函数模板和类模板(但对于函数模板,只有在实例化函数模板时才会出现编译器错误;当编译器遇到第二个类定义时,会立即出现类模板的编译器错误)。

以下是函数模板的示例:

template <unsigned int>
void Foo() {}

template <signed int>    // Same name, only difference is the type of the
void Foo() {}            // non-type template parameter (of integral type)


Foo<10U>(); // COMPILER ERROR.

上面,为什么编译器不能实例化Foo <unsigned int>()?

如果模板函数/类的第二个版本具有类型模板参数,我发现这不是问题。如果模板函数/类的第二个版本具有非整数类型的非类型模板参数,则也不是问题:

template <unsigned int>
void Foo() {}

template <unsigned int*>  // Non-type template parameter
void Foo() {}             // of non-integral type

template <typename T>     // Type template parameter
void Foo() {}


Foo<10U>();               // OK

所以如果我不得不猜测我会说它与编译器可以在整数类型的值之间转换这一事实有关吗?但这并不能阻止C ++允许两个仅由on on integer参数类型不同的重载函数。

谢谢!

c++
1个回答
20
投票

它确实允许它,你能够很好地编写两个模板。它们在实例化时变得无法使用。原因是选择模板没有“重载决议”。对非类型模板参数施加的唯一要求如下:

[temp.arg.nontype]/2

非类型模板参数的模板参数应该是模板参数类型的转换常量表达式。

10uintunsigned int类型的转换常数表达式。作为任一重载的参数有效。

© www.soinside.com 2019 - 2024. All rights reserved.