Skip to content

Instantly share code, notes, and snippets.

@poyenc
Last active December 11, 2015 10:28
Show Gist options
  • Select an option

  • Save poyenc/4586982 to your computer and use it in GitHub Desktop.

Select an option

Save poyenc/4586982 to your computer and use it in GitHub Desktop.
#1G_Ed-0s (C_and_CPP) [ptt.cc]
all: ptt.cc
clang++ ptt.cc -o ptt -lstdc++ -std=c++11 -Wall -W -pedantic && ./ptt
#include <iostream>
#include <type_traits>
struct test {
test() { }
void fun1() { std::cout << "fun1" << std::endl; }
void fun2() const { std::cout << "fun2" << std::endl; }
void fun3() && { std::cout << "fun3" << std::endl; }
};
struct dtest : test {
dtest() { }
};
struct foo {};
namespace detail {
template < typename T >
struct call_proxy_t;
template <>
struct call_proxy_t<int> {
template < typename T >
call_proxy_t( T && t ) {
std::forward<T>( t ).fun1();
}
};
template <>
struct call_proxy_t<float> {
template < typename T >
call_proxy_t( T && t ) {
std::forward<T>( t ).fun2();
}
};
template <>
struct call_proxy_t<double> {
template < typename T >
call_proxy_t( T && t ) {
std::forward<T>( t ).fun3();
}
};
}
template < typename T, typename U >
typename std::enable_if<
std::is_base_of<
test,
typename std::remove_cv<
typename std::remove_reference<U>::type
>::type
>::value
>::type
call_proxy( U && u ) {
detail::call_proxy_t<T>( std::forward<U>( u ) );
}
int main() {
// test base class
test t;
test const ct;
call_proxy<int>( t );
call_proxy<float>( ct );
// test derived class
dtest dt;
dtest const dct;
call_proxy<int>( dt );
call_proxy<float>( dct );
// use temporary object
call_proxy<double>( dtest() );
foo f;
call_proxy<int>( f ); // error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment