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

标签 c++ 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**

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

最佳答案

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> header 是仅 C++11 的 header 。自从您点击 #error标准库中标准版本检查失败后的指令,这是最有可能的罪魁祸首。您不能包含它。

关于c++ - 尝试将 C++11 代码转换为 C++03 时默认函数模板参数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55508736/

相关文章:

c++ - yaml-cpp 库的 API 文档

c++ - 调试 - 检测写入内存位置的函数

c++ - 这是文档中的一个小错误还是我遗漏了什么?

c++ - 如何对 vector 进行二进制搜索以查找具有特定 id 的元素?

c++ - 如何仅在某些时候生成编译器警告?

c++ - 如何在 C++03 中使用自定义谓词调用 std::unique?

c++ - 最佳文件输出缓冲区大小是多少?

c++ - 在 C++03 中是否可以使用非 const 右值引用?

c++ - 当我使用 "Add Definition to xxx.cpp"时,为什么 Qt Creator 使用 std::___LIBCPP_ABI_VERSION::string 而不是 std::string ?这是什么意思?

c++ - gcc 4.9.1 将 c++ 局部变量绑定(bind)到 const auto ref