【问题标题】:Structure specialization when the class has an operator()类具有 operator() 时的结构特化
【发布时间】:2015-12-09 18:36:14
【问题描述】:

当传递的类型具有 operator()(仿函数或 lambda 函数)时,我想专门化一个结构。目前,我有这个代码:

#include <iostream>
#include <type_traits>

template <class...>
struct mystruct: std::false_type {};

template <class C> 
struct mystruct<C, decltype(&C::operator())>: std::true_type {};

int main() {
    int n = 42;
    auto lambda = [&n](int i){return i + n;};

    // Should return false: OK
    std::cout<<mystruct<decltype(x)>::value<<std::endl;

    // Should return true: problem
    std::cout<<mystruct<decltype(lambda)>::value<<std::endl; 

    return 0;
}

如何让它发挥作用?

额外问题:即使operator() 受到保护或私有,如何使其工作?

【问题讨论】:

    标签: c++ templates c++11 metaprogramming template-specialization


    【解决方案1】:

    这将是void_t 技术的适当使用:

    template <class, class = std::void_t<>>
    struct mystruct: std::false_type {};
    
    template <class C> 
    struct mystruct<C, std::void_t<decltype(&C::operator())>>: std::true_type {};
    

    虽然void_t 仅在 C++17 以后的库中,但很容易添加到您自己的实用程序库中。

    关于额外问题,请参阅Detect existence of private member

    【讨论】:

    • 警告:过载或模板化 operator()'s 会中断。
    猜你喜欢
    • 2022-01-21
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多