这是或多或少复制从升压文档粘贴和我不断收到(实际上错误很多)的误差

我想确保模板类只使用升压号码使用。 这是在提升的锻炼,而不是使一个模板类,仅使用数字。

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

前几个错误 C2143:语法错误:缺少 ';'之前 '<':第9行 C2059:语法错误: '<':第9行 C2899:类型名称不能模板声明之外使用

的Visual Studio 2005顺便说一句。

有帮助吗?

解决方案

您从来没有真正创建一个名为A类模板。您刚刚创建了一个专业化的。你需要先用启动器来工作的一个虚拟参数创建A类模板。

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

其他提示

专业的A类模板之前,你必须至少声明。

一个解决方案取决于你想要达到的目标,因为你询问关于帮助的问题是一个试图解决一些问题。

Boost文档enable_if具有这个例子中,这也许是你想要什么:

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

干杯&第h。,

它,因为你缺少在最后的::type。 Enable_if构建体可以是容易出错的时候。我用这个小宏,使其更容易:

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

然后可以写上面的代码是这样的:

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

它有很多对眼睛更容易。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top