Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::enable_if_c does not seem to work [duplicate]

Tags:

c++

boost

sfinae

Possible Duplicate:
How to use enable_if to enable member functions based on template parameter of class

I have a class template:

template<typename T, size_t N> class Vector

I want to enable constructors for specific N, so I do:

Vector(typename boost::enable_if_c<N==2, T>::type const &e0, T const &e1) {
    data[0] = e0;
    data[1] = e1;
}

But compiler (MSVC 2010 SP1) gives me an error instead of applying SFINAE. The error is:

error C2039: 'type' : is not a member of 'boost::enable_if_c<B,T>'
      with
      [
          B=false,
          T=float
      ]

What is the problem? Is it a known problem? How can I fix it? Is it the only solution to use static_assert?

Edit: GCC does not succeed either: http://ideone.com/7Ejo8

like image 914
Juraj Blaho Avatar asked Mar 27 '12 14:03

Juraj Blaho


1 Answers

You can't use enable_if to allow/disallow member functions based on template parameters of the class: enable_if can only be applied on function or class templates.

In your case, the only solution I can think of is specializing the entire class, either using enable_if or more simply with partial specialization. You can put the common members in a common base class, to avoid repeating them:

#include <cstdio>

template<typename T, std::size_t N>
struct VectorCommon
{
  std::size_t size() { return N; }
  void add(T const & element) { }
};

template <typename T, std::size_t N>
struct Vector : VectorCommon<T, N>
{
};

template <typename T>
struct Vector<T, 2> : VectorCommon<T, 2>
{
  Vector(T const & e0, T const & e1) {}
};

int main()
{
  //Vector<int, 100> v100(12, 42); // compile error

  Vector<char, 2> v2('a', 'b');    // ok
}
like image 99
Luc Touraille Avatar answered Nov 14 '22 23:11

Luc Touraille