【发布时间】:2011-10-26 16:39:48
【问题描述】:
我正在尝试检查仿函数是否与给定的一组参数类型和给定的返回类型兼容(即,给定的参数类型可以隐式转换为实际的参数类型,而返回类型则相反) .目前我为此使用以下代码:
template<typename T, typename R, template<typename U, typename V> class Comparer>
struct check_type
{ enum {value = Comparer<T, R>::value}; };
template<typename T, typename Return, typename... Args>
struct is_functor_compatible
{
struct base: public T
{
using T::operator();
std::false_type operator()(...)const;
};
enum {value = check_type<decltype(std::declval<base>()(std::declval<Args>()...)), Return, std::is_convertible>::value};
};
check_type<T, V, Comparer>
这在大多数情况下工作得很好,但是当我测试像struct foo{ int operator()() const;}; 这样的无参数仿函数时它无法编译,因为在这种情况下,base 的两个operator() 显然是模棱两可的,导致这样的事情:
error: call of '(is_functor_compatible<foo, void>::base) ()' is ambiguous
note: candidates are:
note: std::false_type is_functor_compatible<T, Return, Args>::base::operator()(...) const [with T = foo, Return = void, Args = {}, std::false_type = std::integral_constant<bool, false>]
note: int foo::operator()() const
所以显然我需要一种不同的方法来检查无参数仿函数。我尝试为空参数包制作is_functor_compatible 的部分特化,在那里我检查&T::operator() 的类型是否是无参数成员函数,它或多或少地起作用。然而,当被测函子有多个 operator() 时,这种方法显然会失败。
因此我的问题是是否有更好的方法来测试无参数 operator() 的存在以及如何做到这一点。
【问题讨论】:
标签: c++ templates metaprogramming c++11