从控制台读取:运算符>>用于模板类中的枚举

Reading from console: operator>> for enum inside template class

本文关键字:gt 枚举 用于 运算符 读取 控制台      更新时间:2023-10-16

问题的描述非常简单。。。我有一个放在模板类中的枚举(我喜欢它),对于我的应用程序,我需要能够为这个枚举定义运算符>>()函数。。。

然而,这在Visual Studio中产生了一个问题,Microsoft C/C++优化编译器停止工作。换句话说:"编译器中出现内部错误"

再现错误的示例代码:

#include <iostream>
#include <stdexcept>
template <typename T>
struct S{
    enum X { X_A, X_B, X_C };
    template <typename U>
    friend std::istream& operator>>(std::istream& in, enum S<U>::X& x);
};
template <typename U>
std::istream& operator>>(std::istream& in, enum S<U>::X& x)
{
    int a;
    in >> a;
    x = S::X(a);
    return in;
}
int main()
{
    S<int> s;
    S<int>::X x = S<int>::X_A;
    std::cout << "Input: ";
    std::cin >> x;
    std::cout << "Output: " << x << std::endl;
}

如果您能为我们解决这个问题提供帮助,我们将不胜感激!我自己猜测,因为类是模板化的,所以枚举会以某种方式定义多次。。。

这似乎在起作用:

 #include <iostream>
    template< typename T >
    struct S
    {
      enum X
      {
       X_A, X_B, X_C
      };
      friend std::istream& operator>>( std::istream& in, typename S< T >::X & x )
      {
       int a;
       in >> a;
       x = S< T >::X( a );
       return in;
      }
    };
    int main( void )
    {
     S< int > s;
     S< int >::X x = S< int >::X_A;
     std::cout << "Input: ";
     std::cin >> x;
     std::cout << "Output: " << x << std::endl;     
     return( 0 );
    }

test.cpp:在函数'std::istream&运算符>>(std::istream&,枚举S::X&)':
test.cpp:16:错误:在没有模板参数的情况下使用了"模板结构S"

您需要将x = S::X(a);更改为x = S<U>::X(a)