sprintf_s模板库重载不起作用

sprintf_s template base overload not working

本文关键字:重载 不起作用 sprintf      更新时间:2023-10-16

VS2010。我正在将sprintf stmts转换为sprintf_s。我注意到intellisense有两个实现:

int sprintf_s<_Size>(char (&_Dest)[_Size], const char *_Format, ...)
int sprintf_s(char * _DestBuf, size_t _SizeInBytes, const char *_Format, ...)

那么为什么编译器不接受:

void Test(char buf[])
{ 
   sprintf_s<10>(buf, "%s", "test");
}

文档显示您需要定义一个或两个宏来启用这些模板重载。我不认为这些是直接使用的,而是用于在编译时通过C++模板而不是运行时检查静态缓冲区的大小。

如果您想使用模板化版本,其想法是编译器可以从您传递给sprintf_s的参数中推导_Size模板参数,而不是您指定它。

所以基本上,你是这样使用的:

char dest[10];
sprintf_s(dest, "Format %s string", "blah");