abraham_hilbert
abraham_hilbert

Reputation: 2271

Understanding an SFINAE example

I have difficulties to understand SFINAE. For example, I do not understand why the following code does not compile:

#include <iostream>
using namespace std;

// first implementation
template< size_t M, std::enable_if<M==1,size_t>::type = 0>
int foo()
{
  return 1;
}

// second implementation
template< size_t M, std::enable_if<M!=1,size_t>::type = 0>
float foo()
{
  return 1.0f;
}

int main() {
  std::cout << foo<1>() << std::endl;

  return 0;
}

I have expected the following behavior: foo<1> uses the first implementation since std::enable_if < M==1,size_t>::type = 0> causes no substitution error while std::enable_if < M!=1,size_t>::type = 0> does.

Does anyone see the mistake in my argumentation?

Upvotes: 1

Views: 182

Answers (1)

rocambille
rocambille

Reputation: 15976

As stated in the comments, you must add typename before std::enable_if because ::type is a dependent type:

template< size_t M, typename std::enable_if<M==1,size_t>::type = 0>
int foo()
{
  return 1;
}

In C++14, you may use std::enable_if_t, which is an alias to std::enable_if<...>::type, and "embeds" the additional typename:

template< size_t M, std::enable_if_t<M==1,size_t> = 0>
int foo()
{
  return 1;
}

Upvotes: 1

Related Questions