簡體   English   中英

如何將 function 作為參數傳遞,而不管其在 C++ 中的返回類型如何? (不為傳遞的函數使用模板參數)

[英]How can I pass a function as argument regardless of its return type in C++ ? (without using a template parameter for the passed function)

我正在嘗試制作一個 map function。 (回顧:map function 是一個 function,它將 function 應用於集合中的每個項目)

這聽起來很酷,但我希望我的 map function 以任何返回類型作為參數獲得 function。 但是,我不想使用本機代碼片段,例如std::function

與 std::function
請注意,即使使用void返回類型,它也適用於任何輸入 function,無論其返回類型如何(我正在尋找的結果)

#include <functional>
using namespace std;

template <typename T>
void map(function<void(T&)> f, T * collection, unsigned length)
{
    for(unsigned i = 0; i < length; i++)
        f(collection[i]);
}

一種不適用於非 void 返回類型函數的方法

template <typename T>
void map(void (*f)(T&), T * collection, unsigned length)
{
    for(unsigned i = 0; i < length; i++)
        f(collection[i]);
}

我的解決方案

template <typename T, typename any>
void map(any (*f)(T&), T * collection, unsigned length)
{
    for(unsigned i = 0; i < length; i++)
        f(collection[i]);
}

您有不使用第二個模板參數的解決方案嗎?
map 應該如何使用而不考慮其實現(示例):

#include "map.h"
#include <iostream>

void square(int& i){ i *= i; }

int main()
{
    int integers[] = { 5, 3, 2, 9 };

    map(&square, integers, 4);

    for(int i = 0; i < 4; i++)
        std::cout << integers[i] << std::endl;
    
    /*Output:
    25
     9
     4
    81
    */
}
#include <iostream>
#include <vector>
using namespace std;

void m(auto f, auto c)
{
   for(auto i : c)
      f(i);
}
 
int main() {
    m(
        [](int x) { cout << x << '\n'; },
        vector<int>{1, 2, 3});
    return 0;
}

你認為auto是模板嗎? 您可以通過引用使c (和i )可變。

暫無
暫無

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

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