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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With