简体   繁体   English

可变/不可变lambda的编译时开关

[英]Compile-time switch for mutable/immutable lambda

I am writing a class member function that will take a lambda with a given type T in the function argument. 我正在编写一个类成员函数,它将在函数参数中使用给定类型为T的lambda。 My question is: is it possible to overload the member function at compile-time based on the mutability of the argument? 我的问题是:是否可以根据参数的可变性在编译时重载成员函数? Below is the example: 以下是示例:

// T is a given type for class.
template <typename T>
class Wrapper {

  T _t;      

  // For T&
  template <typename F, typename R = std::result_of_t<F(T&)>>
  std::enable_if_t<std::is_same<R, void>::value> operator()(F&& f) {
    f(_t);
  }

  // For const T&
  template <typename F, typename R = std::result_of_t<F(const T&)>>
  std::enable_if_t<std::is_same<R, void>::value> operator()(F&& f) const {
    f(_t);
  }   
};

So, what I want is, if the give lambda is with the following signature, the first operator should be invoked. 所以,我想要的是,如果给出lambda具有以下签名,则应该调用第一个运算符。

[](T&) {
    ...  
};

For constant argument, the second should be invoked. 对于常量参数,应该调用第二个参数。

[](const T&) {
}

If you plan to use non-capturing lambdas only, you can rely on the fact that they decay to pointers to functions. 如果你打算只使用非捕获lambdas,你可以依赖它们衰变到函数指针的事实。
It follows a minimal, working example: 它遵循一个最小的工作示例:

#include<type_traits>
#include<iostream>

template <typename T>
class Wrapper {
    T _t;      

public:
    auto operator()(void(*f)(T &)) {
        std::cout << "T &" << std::endl;
        return f(_t);
    }

    auto operator()(void(*f)(const T &)) const {
        std::cout << "const T &" << std::endl;
        return f(_t);
    }
};

int main() {
    Wrapper<int> w;
    w([](int &){});
    w([](const int &){});
}

Otherwise you can use two overloaded functions as it follows: 否则,您可以使用两个重载函数,如下所示:

#include<type_traits>
#include<iostream>
#include<utility>

template <typename T>
class Wrapper {
    T _t;      

    template<typename F>
    auto operator()(int, F &&f)
    -> decltype(std::forward<F>(f)(const_cast<const T &>(_t))) const {
        std::cout << "const T &" << std::endl;
        return std::forward<F>(f)(_t);
    }

    template<typename F>
    auto operator()(char, F &&f) {
        std::cout << "T &" << std::endl;
        return std::forward<F>(f)(_t);
    }

public:
    template<typename F>
    auto operator()(F &&f) {
        return (*this)(0, std::forward<F>(f));
    }
};

int main() {
    Wrapper<int> w;
    w([](int &){});
    w([](const int &){});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM