简体   繁体   English

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

[英]std::string : Illegal use of this type as an expression

#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
}

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

Why do I get this error and what does it mean in this context? 为什么我会收到此错误,在这种情况下它意味着什么?

The problem is that your code provides two meanings for Nothing and Just : 问题是你的代码为NothingJust提供了两个含义:

  • A value in an enumeration, and 枚举中的值,和
  • A template type 模板类型

The compiler appears to prefer the former; 编译器似乎更喜欢前者; you want the later. 你想要晚一点。

In order to fix this, you could do one of three things: 为了解决这个问题,你可以做以下三件事之一:

  • Rename your enum values, 重命名您的enum值,
  • Rename your template classes, or 重命名模板类,或
  • Make sure that the two colliding names belong to different namespaces. 确保两个冲突名称属于不同的名称空间。

Demo on ideone with the renamed enum constants. 使用重命名的enum常量演示ideone。

Demo on ideone with a separate namespace for the enum . 使用enum的单独命名空间演示ideone。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM