Re: Help with returns_ref_to_const meta-function
On Nov 7, 6:37 am, Edd <e...@nunswithguns.net> wrote:
Hello all,
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)));
};
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;
}
If you don't want to distinguish between const and non-const
references you can get rid of the enableif stuff.
Be aware that it can't distinguish between const values and const
references, but in practice const value returns are uncommon.
Yechezkel Mett
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]