首页 文章

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

提问于
浏览
12

我尝试这个时编译器会出错 . 我试过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参数类型不同的重载函数 .

谢谢!

1 回答

  • 20

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

    [temp.arg.nontype] / 2非类型模板参数的模板参数应为template-parameter类型的转换常量表达式 .

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

相关问题