std命名空间中的重载(而不是特殊化)模板 [英] Overloading (not specializing) templates in std namespace

查看:166
本文介绍了std命名空间中的重载(而不是特殊化)模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是非常迂腐的,但是在C ++ 03中,程序明显不符合重载(不专门 std 命名空间:请参阅此处详细讨论comp.lang.c ++。moderated

This is very pedantic but in C++03 it was apparently non-conforming for a program to overload (not specialize) a template function in the std namespace: see mention of this here and long discussion on comp.lang.c++.moderated

ie这是确定:

namespace std
{
    template <>
    void swap (Foo & f, Foo & g)
    {
       // ...
    }
}

但这不是(如果我正确理解...):

but this was not (if I understand correctly...):

namespace std
{
    template <typename T>
    void swap (TempateFoo<T> & f, TempateFoo<T> & g)
    {
       // ...
    }
}

这在C ++ 11中是否如此?此外,这是否也适用于模板类(如 std :: hash )或只是模板函数?

Is this still true in C++11? Also, does this apply to template classes (like std::hash) too, or just template functions?

编辑:还有,有标准库实现的任何例子,使后者会在实践中打破的东西吗?如果没有,是否有特定的原因不允许重载,像上面的第二种情况? (

also, is there any example of a standard library implementation such that the latter would break things in practice? And if not, is there a specific reason for disallowing overloads like in the second case above? (what could potentially break in theory?)

推荐答案

不可能在C ++中定义函数模板的部分专门化,因此您的第二个示例定义了重载而不是特殊化。由于标准只允许将特殊化添加到命名空间 std ,您的重载是非法的。

It is not possible to define a partial specialization of a function template in C++, so your second example defines an overload not a specialization. Since the standard only allows specializations to be added to namespace std, your overload is illegal.


这在C ++ 11中是否仍然如此?

Is this still true in C++11?

是的。


此外,这是否也适用于模板类(如std :: hash),或只是模板函数?

Also, does this apply to template classes (like std::hash) too, or just template functions?

你不能重载类模板反正,你只能重载函数。同样的规则也适用,但是如果专门化取决于用户定义的(非标准的)类型,则只能专门化类模板。

You can't overload class templates anyway, you can only overload functions. The same rules apply though, you can only specialize a class template if the specialization depends on a user-defined (meaning non-standard) type.


有没有特定的原因不允许重载,像上面的第二种情况? (在理论上可能会出现什么情况?)

is there a specific reason for disallowing overloads like in the second case above? (what could potentially break in theory?)

例如,实现可能需要获取函数的地址, '重载函数,然后取地址可能会导致歧义,无法编译,这意味着你只是在标准库中破坏了有效的代码。

As one example, the implementation might want to take the address of a function but if you've overloaded the function then taking the address could cause an ambiguity and fail to compile, meaning you've just broken valid code in the standard library.

这篇关于std命名空间中的重载(而不是特殊化)模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆