c++ - 检查 std::function 是 std::plus 还是 std::minus

标签 c++

我有一个函数:

bool basicArithmetic(std::function<int(int, int)> func) {
}

如果 funcstd::plusstd::minus 的实例,它应该返回 true但我不知道如何检查。我不能使用 dynamic_cast 因为它不是指针。

最佳答案

您可以使用 target() 成员:

#include <functional>
#include <iostream>

int f(int, int) { return 0; }
int g(int, int) { return 0; }

void test(std::function<int(int, int)> const& arg)
{
    std::cout << "test function:\n";
    if (arg.target<std::plus<int>>()) {
        std::cout << "it is plus\n";
    }
    if (arg.target<std::minus<int>>()) {
        std::cout << "it is minus\n";
    }

    int (*const* ptr)(int, int) = arg.target<int(*)(int, int)>();
    if (ptr && *ptr == f) {
        std::cout << "it is the function f\n";
    }
    if (ptr && *ptr == g) {
        std::cout << "it is the function g\n";
    }
}

int main()
{
    test(std::function<int(int, int)>(std::plus<int>()));
    test(std::function<int(int, int)>(std::minus<int>()));
    test(std::function<int(int, int)>(f));
    test(std::function<int(int, int)>(g));
}

类型测试很简单。测试特定对象似乎并不那么简单:虽然对于原始问题不是必需的,但代码还显示了如何测试函数指针的特定对象。

关于c++ - 检查 std::function 是 std::plus 还是 std::minus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751747/

相关文章:

c++ - GlobalMemoryStatusEx() 给出的总虚拟内存为 127 TeraByte

c++ - 试图编译搅拌库 : error: invalid conversion from ‘const char*’ to ‘char*’

C++ 独立数据的多线程性能

c++ - C++ 20协程的Lambda生命周期说明

C++ 使用指针传递动态创建的数组

c++ - 与指向继承方法的模板化函数指针一起使用的模板化方法的问题

c++ - scanf(%s) EOF 问题

c++ - 在 Ubuntu 上使用 cmake 安装 AWS SDK C++,安装第三方库时出现问题

c++ - moc 文件中缺少信号槽

c++ - 如何让带有 QSqlTableModel 的 QTableView 具有复选框和多行?