从控制台读取:运算符>>用于模板类中的枚举
Reading from console: operator>> for enum inside template class
问题的描述非常简单。。。我有一个放在模板类中的枚举(我喜欢它),对于我的应用程序,我需要能够为这个枚举定义运算符>>()函数。。。
然而,这在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)
。
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 访问在 C++ 结构中声明的枚举变量
- 枚举类'classname'的多重定义
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- typedef 枚举和枚举类有什么区别?
- 为什么我的开关/机箱在使用枚举时默认?
- 标准::可选枚举的比较运算符
- C++两个源文件之间共享的枚举的静态实例
- 打印没有铸件的枚举可以在C++中吗?
- 枚举成员与静态 int 成员?
- C++:枚举:错误:应使用标识符而不是"}"
- 带有 c++ 的枚举(输入检查)
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 为什么 int 类型的枚举类值不能用作 int
- 在 C++ 中输出枚举类类型的向量元素