简体   繁体   English

为什么以下程序会给出“不是类,名称空间或枚举”错误?

[英]Why does the following program give 'is not a class, namespace, or enumeration' error?

In the following program, I expect it::type to be double. 在下面的程序中,我希望it::type为double。 Instead I get the compiler error that it is not a class, namespace, or enumeration . 相反,我得到了it is not a class, namespace, or enumeration的编译器错误。 Based on the other stackoverflow answers to similar questions, this errors seems to be typically seen if you don't instantiate the template with args. 根据类似问题的其他stackoverflow答案,如果不使用args实例化模板,则通常会看到此错误。 I think I am doing that correctly. 我想我做对了。 Could someone please explain, what might be the mistake in the following code? 有人可以解释一下,以下代码可能是什么错误?

#include <iostream>
#include <tuple>

using namespace std;

template <typename ...Ts>
struct list {};

template <int I, typename T, typename ...Ts>
struct S {
        using type = typename S<I-1, Ts...>::type;
};

template <typename T, typename ...Ts>
struct S<0, T, Ts...> {
  using type = T;
};

template <int I, typename ...Ts>
S<I, Ts...> ith(list<Ts...>) {
        return S<I, Ts...>{};
}

int main() {
        auto l = list<const char *, void *, double>{};
        S<2, const char*, void *, double> it = ith<2>(l);
        it::type a = 1; // This line seems to cause the issue, 
                        // if removed the program compiles fine.
        return 0;
}

Error:
p.cpp:32:2: error: 'it' is not a class, namespace, or enumeration
        it::type a = 1;
        ^
p.cpp:31:36: note: 'it' declared here
        S<2, const char*, void *, double> it = ith<2>(l);
                                          ^
1 error generated.

You cannot access a type alias via a variable like that. 您不能通过这样的变量访问类型别名。

Do this instead: 改为这样做:

decltype(it)::type a = 1;

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

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