尝试将C ++ 11代码转换为C ++ 03时默认函数模板参数出错

未定义的行为

我试图将C ++ 11代码转换为C ++ 03,并停留在默认模板参数上。

#include <type_traits>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/spirit/home/support/string_traits.hpp>

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

template<typename T>
struct is_char
{
    typedef typename  enable_if<sizeof (T) == sizeof (char)>::type eif;
};


template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

template <typename ObjType,
        typename PtrType,
        typename CharType =
            typename conditional<boost::is_const<PtrType>::value,
                                      const typename ObjType::char_type,
                                      typename ObjType::char_type>::type,
        typename is_char<PtrType>::type >
CharType* char_ptr_cast(PtrType* p)
{ return reinterpret_cast<CharType*>(p); }

int main ()
{}

我收到以下错误:

> /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/c++0x_warning.h:31:2:
> error: #error This file requires compiler and library support for the
> upcoming ISO C++ standard, C++0x. This support is currently
> experimental, and must be enabled with the -std=c++0x or -std=gnu++0x
> compiler options. 
> 
> test.cc:35: error: no default argument for anonymous
> 
> **default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x**

您能帮我解决这些错误吗?

讲故事的人-Unslander Monica

函数模板的默认模板参数已在C ++ 11中添加。如果您不能使用C ++ 11,或者您的编译器不正确地支持它,则无法定义typename CharType = /* whatever */无需重新键入冗长的元函数即可实现C ++ 03兼容的方法是重构CharType并使用其特有的特征。

template<typename ObjType, typename PtrType>
struct CharType {
    typedef typename conditional<boost::is_const<PtrType>::value,
                                 const typename ObjType::char_type,
                                 typename ObjType::char_type>::type
    type;
};

template <typename ObjType typename PtrType>
typename CharType<ObjType, PtrType>::type* char_ptr_cast(PtrType* p)
{ return reinterpret_cast<typename CharType<ObjType, PtrType>::type*>(p); }

此外,<type_traits>标头是仅C ++ 11的标头。由于您#error在标准库中的标准版本检查失败后命中了指令,因此这很可能是罪魁祸首。您不能包含它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章