我想编写一个is_callable<F, Arg>
定义value
为的 C++ 元函数true
,当且仅当类型 F 具有形式的函数调用运算符时SomeReturnType operator()(const Arg &)
。例如,在以下情况下
struct foo {
void operator(const int &) {}
};
我想is_callable<foo, int &>
成为false
和is_callable<foo, const int &>
成为true
。这是我到目前为止所拥有的:
#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;
}
这打印1
and 1
,但我想要0
and1
因为foo
只定义void operator()(const int &)
.