开发者

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 exerci开发者_Go百科se 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.


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;
};


Before specializing the A class template you would have to at least declare it.

A solution depends on what you're trying to achieve, because the problem you're asking for help about is an attempted solution to some problem.

The Boost documentation of enable_if has this example, which perhaps is what you want:

template <class T, class Enable = void> 
class A { ... };

template <class T>
class A<T, typename enable_if<is_integral<T> >::type> { ... };

template <class T>
class A<T, typename enable_if<is_float<T> >::type> { ... };

Cheers & hth.,


Its because you are missing the ::type at the end. Enable_if construct can be error prone sometimes. I use this little macro to make it easier:

#define CLASS_REQUIRES(...) typename boost::enable_if<boost::mpl::and_<__VA_ARGS__, boost::mpl::bool_<true> > >::type

Then you can write the above code like this:

template <class T, class Enable = CLASS_REQUIRES(is_arithmetic<T>)>
class A 
{
    int foo;
};

Its a lot easier on the eyes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜