prestokeys
prestokeys

Reputation: 4849

Syntax error with typename and scope operator

Can someone tell me how to fix the syntax problem below?

#include <iostream>

template <int N>
struct Thing { 
    static const int num = N;
};

template <int N>
struct Get {
    using type = Thing<N>;
};

template <int... Is>
void foo() {
//  int a[] = {(std::cout << Thing<Is>::num << '\n', 0)...};  // This compiles.
    int a[] = {(std::cout << typename Get<Is>::type::num << '\n', 0)...};  // This does not.
}

int main() {
    foo<0,1,2>();
}

GCC 5.1.0 says [Error] expected '(' before '<<' token. Any quick way to fix this (without writing a new function and have it called within foo)?

Upvotes: 1

Views: 107

Answers (1)

user743382
user743382

Reputation:

As mentioned in the comments already, you don't need typename here. But to explain in a bit more detail:

You probably wrote typename Get<Is>::type::num because you knew that if you would refer to Get<Is>::type, you would need to put typename in front of it. That's generally true, but not always. In some cases, the syntax already makes it crystal clear that type is used as a type, not as an expression, and in that case you don't need typename, and in that case you generally can't use typename.

When you write Get<Is>::type::num, type is already assumed to be a type. Putting typename in front of it indicates that you want num to be treated as a type too. You don't, so don't write typename.

Upvotes: 3

Related Questions