Detecting literal strings, a hack
This must be useful for something?
Yeah, I know: a string class (such as my own). <g>
Anyways, it feels too easy so there must be a catch, but I'm blind. Possibly
could also be done in more elegant way?
<code>
#include <iostream>
class CStringRef {};
class ShouldNotBeCalledDirectly {};
template< size_t N >
CStringRef cStringRefTo(
ShouldNotBeCalledDirectly, char const (&)[N], char *
)
{
std::cout << "Literal" << std::endl;
return CStringRef();
}
template< size_t N >
CStringRef cStringRefTo(
ShouldNotBeCalledDirectly, char const (&)[N], void const *
)
{
std::cout << "Const buffer of size " << N << std::endl;
return CStringRef();
}
template< size_t N >
CStringRef cStringRefTo(
ShouldNotBeCalledDirectly, char (&)[N], char *
)
{
std::cout << "Mutable buffer of size " << N << std::endl;
return CStringRef();
}
CStringRef cStringRefTo( ShouldNotBeCalledDirectly, char const*, ... )
{
std::cout << "Pointer to const" << std::endl;
return CStringRef();
}
CStringRef cStringRefTo( ShouldNotBeCalledDirectly, char*, ... )
{
std::cout << "Pointer to mutable" << std::endl;
return CStringRef();
}
#define CSTR( s ) cStringRefTo( ShouldNotBeCalledDirectly(), s, s )
int main()
{
char const constBuf[] = "const buffer";
char const* constPtr = constBuf;
char mutableBuf[] = "mutable buffer";
char* mutablePtr = mutableBuf;
CSTR( "A literal" );
CSTR( constBuf );
CSTR( mutableBuf );
CSTR( constPtr );
CSTR( mutablePtr );
}
</code>
Cheers,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?