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>
标头是仅限 C++11 的标头。由于您#error
在标准库中的标准版本检查失败后触发了指令,因此这很可能是罪魁祸首。你不能包括它。
推荐阅读
- sql - 对列的一部分应用分组并获得矛盾
- reactjs - 在没有任何构建工具的情况下理解 Kotlin React
- firebase - 从 Firebase 中的 2 个集合中获取数据
- sql - Oracle 文本搜索 - 没有确切长度的模糊结果
- css - 禁用文本选择
- audio - 24kHz 音频文件问题:不支持比特率 64000
- kubernetes - 如何在位于不同区域的两个私有 GCP 集群之间建立通信?
- javascript - 使用 javascript 返回 sqlite 事务
- html - CSS选择器:有没有办法选择整个html中具有相同类名的最后一个元素?
- python - 如何使用 Python startswith 方法来组合 unicode 和 ascii 字符串?