![](/img/trans.png)
[英]Why the following code compiles with `c++03` but not with `c++11`
[英]Error in default function template arguments when trying to convert C++11 code to 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
指令,因此這是最可能的罪魁禍首。 你不能包括它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.