加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么不允许模板专用于不同的命名空间?

发布时间:2020-12-16 03:07:00 所属栏目:百科 来源:网络整理
导读:请看看我正在努力做什么: #include iostreamnamespace first{ template class T class myclass { T t; public: void who_are_you() const { std::cout "first::myclass"; } };}namespace second{ using first::myclass; template class myclass int { int i
请看看我正在努力做什么:
#include <iostream>
namespace first
{
 template <class T>
 class myclass
 { 
  T t;
 public:
  void who_are_you() const
  { std::cout << "first::myclass"; }
 };
}
namespace second
{
 using first::myclass;
 template <>
 class myclass <int>
 {
  int i,j;
 public:
  void who_are_you() const
  { std::cout << "second::myclass"; }
 };
}

这是不允许的.你能否明白为什么专业化不能在不同的命名空间中,什么是可用的解决方案?还有,它是否固定在C 0x?

这将允许我例如,专门使用std :: max,std :: swap,std :: numeric_limits等,而不是通过向:: std ::添加一些东西来诉诸未定义的行为?

@AndreyT这是我如何使用它:

// my_integer is a class
std::numeric_limits<my_integer>::max(); // specialized std::numeric_limits for my_integer

这可以做吗

解决方法

C 2003,§17.4.3.1 / 1:“程序可以为任何标准库模板添加模板专用于命名空间std.标准库模板的这种专门化(完整或部分)导致未定义的行为,除非声明取决于用户定义的外部链接名称,除非专业化符合原始模板的标准库要求.

因此,您可以专门化一个库模板,并将您的专业化命名空间std,只要它取决于用户定义的类型并满足原始模板的要求.

您编辑的问题中的代码似乎是用户定义的名称(可能)具有外部链接的专业化,因此您不应该对该部分的任何问题.

这只会使您的专业化满足原始模板的要求.对于你的类型,大多数这可能是微不足道的.我可以看到的唯一的部分可能不是很明显,你似乎必须为整个模板提供专业化,而不仅仅是numeric_limits :: max().即,你必须做一些事情(例如:128位无符号整数类型的ballpark):

namespace std { 
template <>
class numeric_limits<my_integer> {
public:

    static const bool is_specialized = true;
    static T min() throw() { return 0;
    static T max() throw() { return /* 2^128-1 */; } // ***
    static const int digits = 128;
    static const int digits10 = 38;
    static const bool is_signed = false;
    static const bool is_integer = true;
    static const bool is_exact = true;
    static const int radix = 2;
    static T epsilon() throw() { return 0; }
    static T round_error() throw() { return 0; }
    static const int min_exponent = 0;
    static const int min_exponent10 = 0;
    static const int max_exponent = 0;
    static const int max_exponent10 = 0;
    static const bool has_infinity = false;
    static const bool has_quiet_NaN = false;
    static const bool has_signaling_NaN = false;
    static const float_denorm_style has_denorm = denorm_absent;
    static const bool has_denorm_loss = false;
    static T infinity() throw() { return 0; }
    static T quiet_NaN() throw() { return 0; }
    static T signaling_NaN() throw() { return 0; }
    static T denorm_min() throw() { return 0; }
    static const bool is_iec559 = false;
    static const bool is_bounded = true;
    static const bool is_modulo = true;
    static const bool traps = false;
    static const bool tinyness_before = false;
    static const float_round_style round_style = round_toward_zero;
};
}

其中一些是真正的FP类型,并不需要对整数类型有意义;我相信他们还需要实施.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读