Near a solution

T

Tomás

Tomás posted:
template<class T>
const uchar* ByteAdrs( const T* const p )
{
return reinterpret_cast<const uchar*>(p);
}

template<class T>
unsigned uchar* ByteAdrs( T* const p )
{
return reinterpret_cast<uchar*>(p);
}


Building upon some sample code that Alf P. Steinbach gave me, I've come
up with the following code. It doesn't compile, but I think I'm pretty
close to a solution.

template<class T>
struct DetermineConstness {

/* Two types of differing size: */
struct SizeRepresentModifiable { char c; };
struct SizeRepresentConst { double array[50]; };

static T &ReturnRef(void);

static SizeRepresentModifiable TakesRef(T &);

static SizeRepresentConst TakesRef(const T &);

static bool const is_const =
sizeof( TakesRef( ReturnRef() ) )
== sizeof( SizeRepresentConst );
};

template<bool is_const, class T>
struct ConstnessVersion
{
typedef T Type;
};

template<class T>
struct ConstnessVersion<true, T>
{
typedef T const Type;
};


template<class T>
typename ConstnessVersion<DetermineConstness<T>::is_const, char>::Type
*ByteAdrs( T * const p )
{
return
reinterpret_cast
<typename ConstnessVersion<DetermineConstness<T>::is_const,
char>::Type *>
(p);
}

#include <string>
using std::string;

int main()
{
string str;
string const cstr;

const char *p1 = ByteAdrs(&str); /* No problem */
const char *p2 = ByteAdrs(&cstr); /* No problem */

char *p3 = ByteAdrs(&str); /* No problem */
//char *p4 = ByteAdrs(&cstr); /* ERROR: const clash */
}


Any ideas? Once I get this to work I'll start back on trying to write a
proper "implicit_cast".


-Tomás
 
K

kwikius

Tomás wrote:

Any ideas? Once I get this to work I'll start back on trying to write a
proper "implicit_cast".

What is implicit_cast's purpose? FWIW there is a (currently
undocumented but hopefully documented in next release) function named
implicit_cast in the boost distro. Header is <boost/implicit_cast.hpp>

regards
Andy Little
 
T

Tomás

kwikius posted:
FWIW there is a (currently
undocumented but hopefully documented in next release) function named
implicit_cast in the boost distro. Header is <boost/implicit_cast.hpp>


I downloaded it just there and tried it out... it works perfectly! It's a
stroke of genius! I had to look through the source code to figure out how
it works, but unforunately it's flooded with macros so it would take quite
a while.

It seems that the "identity" template is the magic behind it.


-Tomás
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top