簡體   English   中英

將 std::function 與模板一起使用

[英]Using std::function with templates

所以在最精煉的形式中,我有這樣的事情發生,

template <class T>
bool f(const T &a, const T &b, std::function<bool(const T&, const T&)> func)
{
    return func(a,b);
}

template <class T>
bool g(const T &a, const T &b)
{
    return true;
}  

但是任何調用f()嘗試,無論是f('a', 'b', g) , f(1, 2, g) ,總是導致“沒有匹配的函數調用 'f'”,不管我是否將變量作為常量引用傳遞,或者只是普通值或其他什么。 我假設它無法推斷出一些模板,但我不知道在哪里或為什么。

我承認,我對一般如何使用函數對象的理解非常薄弱,這樣做甚至可能嗎?

參數func被聲明為std::function ,並且您試圖傳遞一個函數指針,這需要隱式轉換。 模板參數推導不考慮隱式轉換,然后推導失敗。

類型推導不考慮隱式轉換(上面列出的類型調整除外):這是重載解析的工作,稍后發生。

你可以顯式地構造一個std::function

f('a', 'b', static_cast<std::function<bool(const char&, const char&)>>(g<char>));

或者顯式指定模板參數(繞過模板參數推導,使隱式轉換稍后生效),

f<char>('a', 'b', g<char>);    

或者只是不使用std::function

template <class T, class F>
bool f(const T &a, const T &b, F func)
{
    return func(a,b);
}

f('a', 'b', g<char>);

我已經為您解決了一些問題,並添加了一些示例。 這應該可以幫助您了解如何使用簡單的 std::function。

#include <iostream>
#include <string>
#include <functional>

template <class T>
bool f(const T &a, const T &b, std::function<bool(const T&, const T&)> func)
{
    return func(a,b);
}

template <class T>
bool g(const T &a, const T &b)
{
    return a==b; // a simple comparator
}  

int main()
{
   int a = 1;
   int b = 1;

   // instantiate f and g as integer type functions
   if( f<int>(a,b,g<int>) == true) 
      std::cout << "true" << std::endl;
   else
      std::cout << "false" << std::endl;

   std::string c="dead";
   std::string d="beef";
   // and now as strings
   if( f<std::string>(c,d,g<std::string>) == true) 
      std::cout << "true" << std::endl;
   else
      std::cout << "false" << std::endl;
   return 0;
}

暫無
暫無

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

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