C++ 関数の引数で関数を受け取り実行する方法

実現したいこと

①関数testの引数として、
②関数f1又は関数f2を受け取り、
③実行したい

試したこと

・質問タイトルの内容で検索してヒットしたサイトの説明を読んで、
自分なりに試してみたのですが関数の実行の仕方が分かりませんでした。
【C++】関数を引数に渡す色々な方法【STL テンプレート 関数ポインタ】

・引数として受け取れているような気がするのですが関数の実行が出来ません。

・warningが出ているのですが検索してもよく分かりませんでした。

warning

/qa2.cpp: In instantiation of ‘int test(T) [with T = int (*)()]’: /QA/qa2.cpp:23:12: required from here /QA/qa2.cpp:16:5: warning: statement has no effect [-Wunused-value] 16 | fn; //実際の処理をする関数 | ^~ * ターミナルはタスクで再利用されます、閉じるには任意のキーを押してください。

コード

C++

#include <bits/stdc++.h>using namespace std; int f1() { cout << "f1" << '\n'; return 0;}int f2() { cout << "f2" << '\n'; return 0;} template <typename T> int test(T fn) { cout << "test:start" << '\n'; //計測開始 fn; //実際の処理をする関数 cout << "test:end" << '\n'; //計測終了 return 0;} int main() { test(f1); test(f2);}

out

//現状の出力 test:start test:end test:start test:end

out

//期待する出力 test:start f1 test:end test:start f2 test:end

補足情報(FW/ツールのバージョンなど)

Ubuntu 20.04 LTS
WSL2
VSCode 1.73.1
Windows10 22H2 19045.2251
C++17
g++ 9.4.0
gdb

コメントを投稿

0 コメント