Re: Help with returns_ref_to_const meta-function
On 7 Nov, 22:34, Yechezkel Mett <ymett.on.use...@gmail.com> wrote:
On Nov 7, 6:37 am, Edd <e...@nunswithguns.net> wrote:
I am trying to create a meta-function to determine whether a function
(with a known identifier) returns a reference-to-const. I can tell if
a reference to non-const is returned, but I cannot distinguish between
the value/ref-to-const cases.
#include <iostream>
template<class T, class V>
struct enableifconst
{};
template<class T, class V>
struct enableifconst<const T, V>
{
typedef V type;
};
template<class T, class V>
struct enableifnonconst
{
typedef V type;};
template<class T, class V>
struct enableifnonconst<const T, V>
{};
template<class Arg>
class Tester
{
typedef char val;
typedef char (&ref_to_nonconst)[2];
typedef char (&ref_to_const)[3];
static Arg& testval;
template<class R>
static typename enableifnonconst<R,
ref_to_nonconst>::type testfunc(R&);
template<class R>
static typename enableifconst<R,
ref_to_const>::type testfunc(R&);
static val testfunc(...);
public:
static const size_t value = sizeof(testfunc(f(testval)));
};
That's the stuff! It failed to compile on MinGW 3.4.5, but I managed
to tweak the code so that it was accepted. It thought the two
templated testfunc()s only different by return type and so could not
be overloaded. The workaround is posted here for Googlers:
#include <iostream>
template<class T>
struct enableifconst
{};
template<class T>
struct enableifconst<const T>
{
typedef int type;
};
template<class T>
struct enableifnonconst
{
typedef int type;
};
template<class T>
struct enableifnonconst<const T>
{};
template<class Arg>
class Tester
{
typedef char val;
typedef char (&ref_to_nonconst)[2];
typedef char (&ref_to_const)[3];
static Arg& testval;
template<class R>
static ref_to_const
testfunc(R&, typename enableifnonconst<R>::type = 0);
template<class R>
static ref_to_nonconst
testfunc(R&, typename enableifconst<R>::type = 0);
static val testfunc(...);
public:
static const size_t value = sizeof(testfunc(f(testval)));
};
double &f(int);
const double &f(float);
double f(bool);
const double f(void*);
int main()
{
std::cout <<
Tester<int>::value << '\n' << // gives 2
Tester<float>::value << '\n' << // gives 3
Tester<bool>::value << '\n' << // gives 1
Tester<void*>::value << '\n'; // also gives 3!
return 0;
}
Be aware that it can't distinguish between const values and const
references, but in practice const value returns are uncommon.
Yeah, that won't be a problem. Thanks very much for your help!
Edd
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]