小编Joe*_*Joe的帖子

C/C++创建一个带负值的枚举,无需编号

例如在C/C++中,我会得到代码:

typedef enum fruits{
   apple,
   banana,
   lemon,
   orange
} fruit_t;
Run Code Online (Sandbox Code Playgroud)

这相当于:

typedef enum fruits{
   apple = 0,
   banana = 1,
   lemon = 2,
   orange = 3
} fruit_t;
Run Code Online (Sandbox Code Playgroud)

但是,我希望这些值是负数,所以它们不会与其他任何东西发生冲突.我可以这样做:

typedef enum fruits{
   apple = -1,
   banana = -2,
   lemon = -3,
   orange = -4
} fruit_t;
Run Code Online (Sandbox Code Playgroud)

但是,如果我想添加另一种水果,我必须分配另一个值,如果我在其中放置一个,我必须重新编号其中的大部分.有更简单的方法吗?

c c++ enums

21
推荐指数
4
解决办法
2万
查看次数

C++模板std :: vector :: iterator错误

在C++中,我试图std::vector::iterator为我的模板化课程.但是,当我编译它时,我得到错误:error C2146: syntax error : missing ';' before identifier 'iterator',error C4430: missing type specifier - int assumed. Note: C++ does not support default-int.我也收到警告warning C4346: 'std::vector<T>::iterator' : dependent name is not a type:

#include <vector>
template<class T> class v1{
    typedef std::vector<T>::iterator iterator; // Error here
};
class v2{
    typedef std::vector<int>::iterator iterator; // (This works)
};
Run Code Online (Sandbox Code Playgroud)

我甚至试过了

template<typename T> class v1{
    typedef std::vector<T>::iterator iterator;
};
Run Code Online (Sandbox Code Playgroud)

template<typename T = int> class v1{
    typedef std::vector<T>::iterator …
Run Code Online (Sandbox Code Playgroud)

c++ templates iterator vector

9
推荐指数
1
解决办法
1万
查看次数

C++ typeid 作为返回类型

有没有办法使用typeid或类似于 C++ 中的返回类型?

例如:

我在类中有一个私有变量,可以设置为任何类型。我怎么能返回它,因为下面的不编译。

#include <type_traits>

typeid(MyVariable) GetValue(){
    return MyVariable;
}
Run Code Online (Sandbox Code Playgroud)

c++ return typeid

6
推荐指数
1
解决办法
4609
查看次数

在异常情况下,C++错误C2228('.''的左边必须有class/struct/union)

在C++中,我试图any用C++ 实现我自己的类.然而,在我能够测试它之前(所以如果我的实现很糟糕,请随意纠正我),我得到了错误:error C2228: left of '.val' must have class/struct/union两次使用该value()函数两次,这在其他地方工作时看起来很奇怪.我唯一能想到的是decltype函数的前面是导致错误,但它不应该:

编辑:我已经更新了更改template<class T> any(T V){...}构造函数变量的方法

class any{
protected:
    template<class T> struct variable{
    public:
        T val;
        variable(){}
        variable(T t) : val(t){}
    };
    variable<int> v;
public:
    any(){
        v.val = 0;
    }
    template<class T> any(T V){
        variable<T> nV(V);
        v = nV;
    }
    ~any(){
        delete &v;
    }
    decltype(v.val) value(){ // Error still here
        return v.val;
    }
    template<class T> static any create(T V){
        return any(V);
    }
};
Run Code Online (Sandbox Code Playgroud)

c++ struct decltype any c++11

4
推荐指数
1
解决办法
1030
查看次数

标签 统计

c++ ×4

any ×1

c ×1

c++11 ×1

decltype ×1

enums ×1

iterator ×1

return ×1

struct ×1

templates ×1

typeid ×1

vector ×1