How do I determine if a type is callable with only const references?
-
29-10-2019 - |
Question
I want to write a C++ metafunction is_callable<F, Arg>
that defines value
to be true
, if and only if the type F has the function call operator of the form SomeReturnType operator()(const Arg &)
. For example, in the following case
struct foo {
void operator(const int &) {}
};
I want is_callable<foo, int &>
to be false
and is_callable<foo, const int &>
to be true
. This is what I have so far :
#include <memory>
#include <iostream>
template<typename F, typename Arg>
struct is_callable {
private:
template<typename>
static char (&test(...))[2];
template<unsigned>
struct helper {
typedef void *type;
};
template<typename UVisitor>
static char test(
typename helper<
sizeof(std::declval<UVisitor>()(std::declval<Arg>()), 0)
>::type
);
public:
static const bool value = (sizeof(test<F>(0)) == sizeof(char));
};
struct foo {
void operator()(const int &) {}
};
using namespace std;
int main(void)
{
cout << is_callable<foo, int &>::value << "\n";
cout << is_callable<foo, const int &>::value << "\n";
return 0;
}
This prints 1
and 1
, but I want 0
and 1
because foo
only defines void operator()(const int &)
.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow