Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <type_traits>
- #include <iostream>
- template <typename T, bool b = std::is_function<T>::value>
- struct is_callable {
- static const bool value = true;
- };
- template <typename T>
- struct is_callable <T, false> {
- // Types "yes" and "no" are guaranteed to have different sizes,
- // specifically sizeof(yes) == 1 and sizeof(no) == 2.
- typedef char yes[1];
- typedef char no[2];
- struct check_helper {
- operator T();
- };
- template <typename TYPE>
- struct helper {
- operator TYPE();
- };
- // template <typename C>
- // static yes& test(decltype(C()())*);
- template <typename C>
- static yes& test( decltype( static_cast<C>( check_helper() ) () )*);
- template <typename>
- static no& test(...);
- // If the "sizeof" the result of calling test<T>(0) would be equal to the sizeof(yes),
- // the first overload worked and T has a nested type named foobar.
- static const bool value = sizeof(test<T>(0)) == sizeof(yes);
- };
- template <typename T, typename T2, bool b = std::is_function<T>::value>
- struct is_callable_1 {
- static const bool value = true;
- };
- template <typename T, typename T2>
- struct is_callable_1<T, T2, false> {
- // Types "yes" and "no" are guaranteed to have different sizes,
- // specifically sizeof(yes) == 1 and sizeof(no) == 2.
- typedef char yes[1];
- typedef char no[2];
- struct check_helper {
- operator T();
- };
- template <typename TYPE>
- struct helper {
- operator TYPE();
- };
- template <typename C>
- static yes& test( decltype( static_cast<C>( check_helper() ) ( helper<T2>() ) )*);
- template <typename>
- static no& test(...);
- // If the "sizeof" the result of calling test<T>(0) would be equal to the sizeof(yes),
- // the first overload worked and T has a nested type named foobar.
- static const bool value = sizeof(test<T>(0)) == sizeof(yes);
- };
- class Class {
- public:
- void operator() () {}
- };
- class Op {
- public:
- void operator() (int) {}
- void operator() () {}
- };
- void blah (int a = 0) {}
- int main() {
- std::cout << "callable 0" << std::endl;
- std::cout << is_callable<decltype(blah)>::value << std::endl;
- std::cout << is_callable<Class>::value << std::endl;
- std::cout << is_callable<Op>::value << std::endl;
- std::cout << is_callable<int>::value << std::endl;
- std::cout << "callable int" << std::endl;
- std::cout << is_callable_1<decltype(blah), int>::value << std::endl;
- std::cout << is_callable_1<Class, int>::value << std::endl;
- std::cout << is_callable_1<Op, int>::value << std::endl;
- std::cout << is_callable_1<int, int>::value << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement