簡體   English   中英

C++ 模板 function,指定回調函子/lambda 的參數類型,同時仍允許內聯?

[英]C++ template function, specify argument type of callback functor/lambda while still allow inlining?

我們通常做的事情是這樣的:

template<class Callback>  
void some_func(Callback const& callback){
   ....
}

我想要的是這樣的:

template<class void Callback(int)>  //<---
void some_func(Callback const& callback){// not valid
   ....
}

如果我們通過std::function傳遞,我們可以指定類型,但它會禁用內聯。

如果你有 C++20 這正是這些概念的用途

#include <concepts>

template<typename T>
concept Callback = requires(T a) {
    { a(int()) }  -> std::same_as<void>; 
};

template<Callback T> 
void some_func(T const& callback){
  //  ....
}

int a(int) {
    return 0;
}

void b(int) {}

int main() {
    // below does not compile
   // some_func(a);
    some_func(b);
}

您可以將std::enable_ifstd::is_invocable 一起使用(需要 C++17 但可以在 C++ 14 中實現):

#include <type_traits>
#include <iostream>
#include <string>

template <typename F,
          typename = std::enable_if_t<std::is_invocable_v<F, int>>>
void foo(F&& f)
{
    f(1);
}

int main()
{
    // OK
    foo([](int x) { std::cout << x << std::endl; });

    // Still compiles since int is convertible to double
    foo([](double x) { std::cout << x << std::endl; });

    // Compilation error
    // in gcc:
    // error: no matching function for call to 'foo(main()::<lambda(std::string)>)'
    foo([](std::string x) { std::cout << x << std::endl; });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM