Search code examples
c++boostenable-if

Boost enable_if problem


This is more or less copy pasted from boost docs and I keep getting an error (actually alot of errors)

I'm trying to make sure that a template class is only used with numbers using boost. This is an exercise in boost, rather than making a template class that only uses numbers.

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>

using namespace boost;

template <class T>
class A<T, typename enable_if<is_arithmetic<T> >::type> // <-- this is line 9
{
    int foo;
};

int main() {

    return 0;
}

The first few errors C2143: syntax error : missing ';' before '<' : line 9 C2059: syntax error : '<' : line 9 C2899: typename cannot be used outside a template declaration

Visual Studio 2005 btw.


Solution

  • You never actually created a class template called A. You just created a specialization. You need to first create the A class template with a dummy parameter for the enabler to work.

    using namespace boost;
    
    template <class T, class Enable = void>
    class A { };
    
    template <class T>
    class A<T, typename enable_if<is_arithmetic<T> >::type> 
    {
        int foo;
    };