簡體   English   中英

模板函數中的itoa

[英]itoa in a template function

代碼優先:

template <typename T>
void do_sth(int count)
{
    char str_count[10];
    //...
    itoa(count, str_count, 10);
    //...
}

但是我遇到了一些這樣的編譯錯誤:

error: there are no arguments to ‘itoa’ that depend on a template parameter, so a declaration of ‘itoa’ must be available
error: ‘itoa’ was not declared in this scope

但是我確實包括了<cstdlib> 誰能告訴我怎么了?

它是一個非標准函數,通常在stdlib.h定義(但ANSI-C並沒有對此提供保證,請參見下面的注釋)。

#include<stdlib.h>

然后使用itoa()

請注意, cstdlib沒有此功能。 因此,包括cstdlib將無濟於事。

另請注意, 此在線文檔說,

可移植性

此函數未在ANSI-C中定義,也不屬於C ++,但某些編譯器支持。

如果它是在標頭中定義的,那么在C ++中,如果必須將其用作:

extern "C" 
{
    //avoid name-mangling!
    char *  itoa ( int value, char * str, int base );
}

//then use it
char *output = itoa(/*...params*...*/);

便攜式解決方案

您可以使用sprintf將整數轉換為字符串,如下所示:

sprintf(str,"%d",value);// converts to decimal base.
sprintf(str,"%x",value);// converts to hexadecimal base.
sprintf(str,"%o",value);// converts to octal base.

看來itoa是非標准功能,並非在所有平台上都可用。 請改用snprintf(或類型安全的std :: stringstream)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM