C++ 在传递函数值或函数指针时是否可以使用一致的语法

问题描述 投票:0回答:1

由于类型(函数与函数指针)在编译时已知,是否可以使用一致的语法来选择所需的重载?

using Function = void(*)();

void foo(){}        // Function
Function bar = foo; // Function pointer

// In C++ one may pass a function as a value template
template<Function function> void impl()
{
    function(); // (Optimal) Known at compile time
}

// Or pass a function as a function pointer
void impl(Function function)
{
    function(); // Known at runtime
}

int main()
{
    impl<foo>(); // Good. Function value
    impl(foo);   // Bad. Function pointer.  foo should use impl<foo>()
    impl(bar);   // Good. Function pointer. bar is a function pointer
    impl<bar>(); // Bad. Fails to compile

// Psudocode for desired result
    #define BIND(x) (is_function<decltype(x)> ? impl<x>() : impl(x))
    BIND(foo);
    BIND(bar);
    // This does not work with std::is_function_v() because of the compiler error when passing a function pointer in the impl<x>() case
}

我的用例是实现“难以置信的快速代表”。 我希望它们能够高效、无缝地处理函数和函数指针。

我已经尝试过:

  • 模板
  • constexpr 函数指针
  • 如果 constexpr()
  • 保守
  • if consteval() // c++23

这是编译时信息,为什么我被迫在 <> 和 () 之间手动选择? 这是语言语法的限制吗?

c++ function syntax delegates
1个回答
0
投票
#define BIND(x) \
    do { \
        if constexpr(requires{ impl<(x)>(); }) \
            impl<(x)>(); \
        else \
            impl((x)); \
    } while(false);

requires{ impl<(__VA_ARGS__)>(); }
只是告诉您该形式是否可行,然后如果可以则使用它,如果不可以则使用另一种形式。

然而,使用没有宏的统一语法这是不可能的。模板参数和函数参数是根本不同的,并且对于类型系统具有完全不同的含义。编译器无法“猜测”您的意思。

© www.soinside.com 2019 - 2024. All rights reserved.