检测模板化操作符()的限定符

Detect qualifiers of templated operator()

本文关键字:操作符 检测      更新时间:2023-10-16

我正在寻找一个特征来检测和提取模板化operator()的完整签名(检查方法限定符volatileconst)。

表示std::bind表达式(不使用std::is_bind_expression)和带有自动参数的lambda。预期的返回类型和参数是已知的

例如:

template<typename Fn, typename T>
struct is_templated_functor { ... };
auto fun = [](auto) mutable { };
using ty = decltype(&decltype(fun)::operator()<int>);
// ty = void(decltype(fun)::*)(int)
// lambda is mutable ~~~~~~~~~~~~~~~^^^^^^
is_templated_functor<void(int), decltype(fun)>::value == true;
auto fun2 = std::bind([](int) { });
using ty2 = decltype(&decltype(fun2)::operator()<int>);
// ty2 = void(decltype(fun2)::*)(int) const
is_templated_functor<void(int), decltype(fun2)>::value == true;

由于@Yakk的评论,我意识到我不需要获得表达式的完整签名来检查表达式是否可以使用const和/或volatile限定符调用,因为返回类型和参数已经已知。

可以使用检测组来检查具有模板化operator()的对象是否可以用给定的限定符调用:

template<typename Fn>
struct impl_is_callable_with_qualifiers;
template<typename ReturnType, typename... Args>
struct impl_is_callable_with_qualifiers<ReturnType(Args...)>
{
    template<typename T>
    static auto test(int)
        -> typename std::is_convertible<
            decltype(std::declval<T&>()(std::declval<Args>()...)),
            ReturnType
           >;
    template<typename T>
    static auto test(...)
        -> std::false_type;
};
template<bool Condition, typename T>
using add_const_if_t = typename std::conditional<
    Condition,
    typename std::add_const<T>::type,
    T
>::type;
template<bool Condition, typename T>
using add_volatile_if_t = typename std::conditional<
    Condition,
    typename std::add_volatile<T>::type,
    T
>::type;
template<typename T, typename Fn, bool Constant, bool Volatile>
using is_callable_with_qualifiers = decltype(impl_is_callable_with_qualifiers<Fn>::template test<
    add_volatile_if_t<Volatile, add_const_if_t<Constant, typename std::decay<T>::type>>
>(0));

使用例子:

struct callable
{
    void huhu(int) const { }
};
auto fun = [](auto) mutable { };
static_assert(is_callable_with_qualifiers<decltype(fun), void(int), false, false>::value, "1 failed");
static_assert(!is_callable_with_qualifiers<decltype(fun), void(int), true, true>::value, "2 failed");
auto fun2 = std::bind(&callable::huhu, callable{}, std::placeholders::_1);
// std::bind isn't const correct anyway...
static_assert(is_callable_with_qualifiers<decltype(fun2), void(int), false, false>::value, "3 failed");
static_assert(is_callable_with_qualifiers<decltype(fun2), void(int), true, false>::value, "4 failed");
static_assert(!is_callable_with_qualifiers<decltype(fun2), void(int), true, true>::value, "5 failed");