Last active
March 9, 2016 15:40
-
-
Save meetingcpp/b1b90f2be96897896ef5 to your computer and use it in GitHub Desktop.
Example code for selecting by interface via enable_if/return type deduction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <type_traits> | |
#include <boost/tti/has_member_function.hpp> | |
#include <boost/function_types/result_type.hpp> | |
struct Interface | |
{ | |
std::string interface()const | |
{ | |
return "interface"; | |
} | |
}; | |
struct my_interface | |
{ | |
std::string get_my_interface()const | |
{ | |
return "get_my_interface"; | |
} | |
}; | |
struct myInterfaceType | |
{ | |
int myInterface()const | |
{ | |
return 42; | |
} | |
}; | |
namespace foo | |
{ | |
namespace detail | |
{ | |
BOOST_TTI_HAS_MEMBER_FUNCTION(interface) | |
BOOST_TTI_HAS_MEMBER_FUNCTION(get_my_interface) | |
BOOST_TTI_HAS_MEMBER_FUNCTION(myInterface) | |
} | |
template<typename Interface> | |
struct GenericInterface | |
{ | |
template<class T = Interface> | |
auto query_interface() const -> decltype(std::declval<T>().interface()) | |
{ | |
return i.interface(); | |
} | |
//OR | |
/* | |
template<class T = Interface> | |
std::enable_if< detail::has_member_function_interface<std::string (T::*)()const,void>::type query_interface()const | |
{ | |
return i.interface(); | |
}*/ | |
template<class T = Interface> | |
auto query_interface() const -> decltype(std::declval<T>().get_my_interface()) | |
{ | |
return i.get_my_interface(); | |
} | |
template<typename T = Interface > | |
auto query_interface()const -> decltype(std::declval<T>().myInterface(),int()) | |
{ | |
return i.myInterface(); | |
} | |
void print() | |
{ | |
std::cout << query_interface() << "\n"; | |
} | |
private: | |
Interface i; | |
}; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
foo::GenericInterface<Interface> gInterface; | |
foo::GenericInterface<my_interface> gmy_interface; | |
foo::GenericInterface<myInterfaceType> gmyInterface; | |
gInterface.print(); | |
gmy_interface.print(); | |
gmyInterface.print(); | |
std::cout << std::boolalpha <<foo::detail::has_member_function_get_my_interface<std::string (my_interface::*)()const>::value << std::endl; | |
std::cout << std::boolalpha <<foo::detail::has_member_function_interface<myInterfaceType,std::string>::value << std::endl; | |
std::cout << std::boolalpha << foo::detail::has_member_function_interface<std::string (Interface::*)()const>::value << std::endl; | |
static_assert(foo::detail::has_member_function_interface<std::string (Interface::*)()const>::value,"fail"); | |
std::cout << "Hello World!" << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment