【问题标题】:VC++ Class Templates Implementing Function with typedef TypeVC++ 类模板用 typedef 类型实现函数
【发布时间】:2017-05-04 13:08:25
【问题描述】:

我现在有一些奇怪的事情发生。我正在尝试使用 VC++ 编译器编写模板类。

在我的课堂上,为了清楚起见,我得到了一些 typedef。我在头文件之外的实际实现

template<typename T,
    typename = typename std::enable_if<std::is_arithmetic<T>::value,T>::type>
class Integer
{
public:
    typedef  T                      value_type;
    typedef  Integer < value_type > Self;
    typedef  Self&                  SelfReference;
    typedef  Self*                  SelfRawPointer;
    ...
public:
    SelfReference operator =(const SelfReference);

*.tcc - 文件:

...
template<typename T> Integer<T>::SelfReference Integer<T>::operator =(const 
Integer<T>::SelfReference rhs)
{
    return this->assign(rhs);
};
...

过去使用 gcc 我没有任何问题,但现在在 Windows 上编译器抱怨 'SelfReference':C2061: syntax error: identifier 'SelfReference'

我不知道出了什么问题,因为在过去使用 gcc 时它工作...我错过了什么吗?如果我内联编写函数,则不会出现问题。我现在只是好奇为什么在 Windows 上我会遇到这种问题!

【问题讨论】:

    标签: c++ templates visual-c++


    【解决方案1】:

    SelfReference是依赖类型,所以需要使用typename

    template <typename T>
    typename Integer<T>::SelfReference Integer<T>::operator=(const typename Integer<T>::SelfReference rhs) { blah; }
    

    Integer&lt;T&gt;::的右边你也可以只使用SelfReference,即。

    template <typename T>
    typename Integer<T>::SelfReference Integer<T>::operator=(const SelfReference rhs) { blah; }
    

    这是 c++11 中 auto 返回值的部分原因,您现在可以编写

    template <typename T>
    auto Integer<T>::operator=(const SelfReference rhs) -> SelfReference
    {
         blah;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多