std::string:将此类型非法用作表达式

std::string : Illegal use of this type as an expression

本文关键字:表达式 非法 string std 类型      更新时间:2023-10-16
#include <functional>
#include <string>
enum MaybeType{
  Nothing,
  Just
};
template<typename T>
class Maybe{
  virtual MaybeType getType() const = 0;
};
template<typename T>
class Just : public Maybe<T>{
  T value;
  virtual MaybeType getType() const{
    return MaybeType::Just;
  }
public:
  Just(T v) : value(v){}
};
template<typename T>
class Nothing : public Maybe<T>{
  virtual MaybeType getType() const{
    return MaybeType::Nothing;
  }
};
int main(){
  using namespace std;
  string s = "Hello";
  auto m = Just<string>(s); // error
}

我得到以下错误"std::string"error C2275: 'std::string' : illegal use of this type as an expression

为什么我会出现这个错误,在这种情况下它意味着什么?

问题是您的代码为NothingJust提供了两种含义:

  • 枚举中的值,以及
  • 模板类型

编译器似乎更喜欢前者;你想要晚一点。

为了解决这个问题,你可以做三件事之一:

  • 重命名您的enum
  • 重命名模板类,或者
  • 请确保两个冲突的名称属于不同的名称空间

使用重命名的enum常量在ideone上演示。

在ideone上演示enum的独立命名空间。