我正在使用android NDK r9d和ToolChain4.8,但是我不能使用std::to_string函数,编译器抛出这个错误:
error: 'to_string' is not a member of 'std'
android ndk不支持此功能吗?我尝试过APP_CPPFLAGS := -std=c++11
,但没有成功。
发布于 2014-04-01 09:32:21
您可以尝试使用LOCAL_CFLAGS := -std=c++11
,但请注意not all C++11 APIs are available with the NDK's gnustl。libc++ (APP_STL := c++_shared
)提供完整的C++14支持。
另一种方法是自己实现它。
#include <string>
#include <sstream>
template <typename T>
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
int main()
{
std::string perfect = to_string(5) ;
}
发布于 2014-12-19 17:33:51
有了NDK r9+,你可以使用llvm-libc++,它提供了对cpp11的完全支持。
在您的Application.mk中,您必须添加:
APP_STL:=c++_static
或
APP_STL:=c++_shared
发布于 2018-01-26 04:40:46
我不能使用c++_static
,它给出了一些关于未定义异常的错误。所以我又回到了gnustl_static
。
但是在NDK源代码中,在sources/cxx-stl/llvm-libc++/src/string.cpp
中,我找到了to_string(int)
的实现,并尝试将其复制到我的代码中。经过一些修正后,它起作用了。
所以我的最后一段代码:
#include <string>
#include <algorithm>
using namespace std;
template<typename S, typename P, typename V >
inline
S
as_string(P sprintf_like, S s, const typename S::value_type* fmt, V a)
{
typedef typename S::size_type size_type;
size_type available = s.size();
while (true)
{
int status = sprintf_like(&s[0], available + 1, fmt, a);
if ( status >= 0 )
{
size_type used = static_cast<size_type>(status);
if ( used <= available )
{
s.resize( used );
break;
}
available = used; // Assume this is advice of how much space we need.
}
else
available = available * 2 + 1;
s.resize(available);
}
return s;
}
template <class S, class V, bool = is_floating_point<V>::value>
struct initial_string;
template <class V, bool b>
struct initial_string<string, V, b>
{
string
operator()() const
{
string s;
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, false>
{
wstring
operator()() const
{
const size_t n = (numeric_limits<unsigned long long>::digits / 3)
+ ((numeric_limits<unsigned long long>::digits % 3) != 0)
+ 1;
wstring s(n, wchar_t());
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, true>
{
wstring
operator()() const
{
wstring s(20, wchar_t());
s.resize(s.capacity());
return s;
}
};
string to_string(int val)
{
return as_string(snprintf, initial_string<string, int>()(), "%d", val);
}
https://stackoverflow.com/questions/22774009
复制相似问题