Boost enable_if problem

杀马特。学长 韩版系。学妹 提交于 2019-12-24 23:18:43

问题


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.


回答1:


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



回答2:


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.,




回答3:


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.



来源:https://stackoverflow.com/questions/4068286/boost-enable-if-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!