简体   繁体   中英

Why doesn't this simple enable_if work?

I'm having a problem with an enable_if construct which I've managed to reduce to a very simple piece of failing code:

template <typename Enable, typename...Args>                                 
struct Get;                                                     

template <typename FirstArg, typename... OtherArgs>                       
struct Get<typename std::enable_if<true>::type, FirstArg, OtherArgs...>
{                                                                               
    using type = FirstArg;                                                          
};                                                                              

( Live example )

The above code is a gutted version of some code that did something useful, but for the sake of this question I'm more interested in why this doesn't work, not whether or not it's ideal or does anything useful. The meta function Get should take the first type passed to it and, based on some condition (in this case always true as I didn't construct a case for when it is not) return it.

I don't want the first argument to resolve to the enable_if condition, that should be completely abstracted.

When I try to run this (see live example) it produces

error: 'type' in 'struct Get' does not name a type using T = typename Get::type

Why?

The specialization you wrote only kicks in if someone passed void as the first argument to Get .

In your example code, you passed int . So the specialization does not apply.

The names of the types in the template definition and specialization have no connection, just their position in the Get<blah, blah, blah> . And it is pattern matching off the primary definition.

int main() {
  using T = Get<void, int>::type;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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