c++ - 确定仿函数的参数和结果类型

标签 c++ functor sfinae

我如何测试仿函数是否是一个可调用对象,它引用一个 int 并返回一个 bool?

template<typename functor>
void foo(functor f)
{
    static_assert('functor == bool (int&)', "error message");

    int x = -1;
    if (f(x))
        std::cout << x << std::endl;
}

bool bar(int& x)
{
    x = 4711;
    return true;
}

struct other
{
    bool operator()(int& x)
    {
        x = 815;
        return true;
    }
};

最佳答案

在我看来,您并不是真的想检查仿函数的签名,而是首先要限制用户可以传入的内容:

如果您有权访问 std::function,您可以这样做:

void foo(const std::function<bool(int&)>& f)

关于c++ - 确定仿函数的参数和结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014505/

相关文章:

functional-programming - Functor 和 Monad 有什么区别?

c++ - 仿函数调用(附加字符)

c++ - 拥有 [[nodiscard]] 类型的理由是什么?

c++ - 在 C++ 中从 [0,1] 获取随机双数

C++ 为什么链接器看不到我的文件?

haskell - "deriving Functor"究竟是做什么的?

c++ - 如何使用 gtk 中的代码将单选按钮设置为选中状态?

c++ - const 和非 const 类型的相同模板特化

c++ - 检查 C++ 成员函数是否存在,可能 protected

c++ - 为什么 `std::enable_if` 需要默认值?