Verify type of string (e.g. literal, array, pointer) passed to a function [duplicate]
I have a function, which takes a character array and its size:
void store_string (const char *p, size_t size); // 'p' & 'size' stored in map
The function is wrapped by a macro as:
#define STORE_STRING(X) store_string(X, sizeof(X))
My problem is that I want to somehow prohibit or inform user that only string literal should be passed to this function. Because, if any pointer or local array are stored inside the map then they might go out of scope and create a havoc!
Is there any compile-time way (preferred) or at least run-time way to do it?
You can know it compile time, by simply changing your macro to:
#define STORE_STRING(X) store_string("" X, sizeof(X))
Usage:
char a[] = "abcd", *p;
STORE_STRING(a); // error
STORE_STRING(p); // error
STORE_STRING("abcd"); // ok
This does not work, sizeof(char *) returns the size of the pointer not the memory allocated or string size.
strlen(x) returns the size of a string by looking for the '\0'.
If you need/want a non-macro solution there is one template trick that can help. You can have a function signature that looks like this:
template<int len>
void store_string( char const (&str)[len] ) { store_string_internal( str,len); }
template<int len>
void store_string( char (&str)[len] ) { static_assert( false ); }
The first form accepts strings literals and calls the target function. The second form prevents non-const character arrays from being passed. And yeah, don't offer a char const*
version.
This doesn't guarantee that the string is a string literal, but the one syntax needed to bypass it is extremely rare (I've never used it).
Otherwise the macro version from iammilind is nice.
精彩评论