Skip to content

Instantly share code, notes, and snippets.

@kennethho
Last active December 11, 2015 21:18
Show Gist options
  • Save kennethho/4661046 to your computer and use it in GitHub Desktop.
Save kennethho/4661046 to your computer and use it in GitHub Desktop.
// ref: https://plus.google.com/u/0/111121989384217966500/posts/LjSZjmKGpjj
// Tested with gcc 4.6.3
// $ g++ -std=c++0x THISFILE && a.out
#include <cassert>
#include <type_traits>
using namespace std;
template <typename T>
struct get_impl;
template <>
struct get_impl<int>
{
static int call()
{
return 0;
}
};
template <>
struct get_impl<double>
{
static double call()
{
return 1.0;
}
};
struct auto_getter
{
template <typename T>
operator T () const
{
return get_impl<T>::call();
}
};
template <typename T>
T get()
{
return get_impl<T>::call();
}
inline auto_getter get()
{
return auto_getter{};
}
int f(int)
{
return 0;
}
int f(double)
{
return 1;
}
void example()
{
{
int a = get();
assert(a == 0);
double b = get();
assert(b == 1.0);
}
{
auto a = get<int>();
assert(a == 0);
auto b = get<double>();
assert(b == 1.0);
}
assert(f(get<int>()) == 0);
assert(f(get<double>()) == 1);
// <dont_do_this>
auto c = get();
bool c_is_auto_getter = is_same<decltype(c), auto_getter>::value;
assert(c_is_auto_getter);
int d = c;
assert(d == 0);
double e = c;
assert(e == 1.0);
// </dont_do_this>
//string x = get(); // compile-time error
//auto y = get<string>();// compile-time error
}
int main()
{
example();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment