首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检测模板化操作符()的限定符

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

Stack Overflow用户
提问于 2015-09-11 14:44:08
回答 1查看 159关注 0票数 0

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

这意味着std::bind表达式(不使用std::is_bind_expression)和带有auto参数的lambda。预期的返回类型和参数是已知的

例如:

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-11 16:51:38

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

可以使用检测白痴来检查模板化operator()的对象是否可以用给定的量词调用:

代码语言:javascript
复制
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));

用法示例:

代码语言:javascript
复制
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");

Demo

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32526163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档