Created
December 18, 2012 16:15
-
-
Save alexeiz/4329358 to your computer and use it in GitHub Desktop.
Test if a type is a callable, i.e. objects of that type can be called as functions. Also shows how to do type tests with decltype instead of sizeof.
This file contains hidden or 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 <type_traits> | |
template<typename F, typename ...Ts> | |
class is_callable | |
{ | |
template<typename G, typename ...Us> | |
static | |
decltype( | |
typename std::add_pointer<decltype(std::declval<G>()(std::declval<Us>()...))>::type{}, | |
std::true_type{}) | |
test(int); | |
template<typename, typename ...> | |
static | |
std::false_type test(...); | |
public: | |
static constexpr bool value = decltype(test<F, Ts...>(0))::value; | |
}; | |
void test() {} | |
void test1(int) {} | |
int main() | |
{ | |
static_assert(is_callable<decltype(test)>::value, "test() - OK"); | |
static_assert(! is_callable<decltype(test), int>::value, "test(int) - error"); | |
static_assert(! is_callable<decltype(test1)>::value, "test1() - error"); | |
static_assert(is_callable<decltype(test1), int>::value, "test1(int) - OK"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment