目前尚不清楚你想達到什麼目的,但這裏有一個例子說明你的代碼可以如何轉換成有效的C++。首先,讓我們來定義你的Func
用的參數最大數量:
template<typename T1, typename T2>
void Func(T1 par1, T2 par2) {
std::cout << par1 << " " << par2 << std::endl;
}
那麼我們應該FuncFunc
接受任何功能,你想:
template<typename ...T>
void FuncFunc(const std::function<void(T...)>& fPtr) {
std::string funcVar = "Foo!";
fPtr(funcVar);
}
或更易於使用的變體:
template<typename F>
void GuncFunc(const F& fPtr) {
std::string funcVar = "Foo!";
fPtr(funcVar);
}
最後用FuncFunc
:
auto Func1 = std::bind(Func<float, std::string>, 3.14f, std::placeholders::_1);
auto Func2 = std::bind(Func<std::string, int>, std::placeholders::_1, 42);
FuncFunc(std::function<void(std::string)>(Func1));
FuncFunc(std::function<void(std::string)>(Func2));
return 0;
或GuncFunc
:
// Using std::bind
GuncFunc(std::bind(Func<float, std::string>, 3.14f, std::placeholders::_1));
GuncFunc(std::bind(Func<std::string, int>, std::placeholders::_1, 42));
// Or using lambdas:
GuncFunc([](std::string s){Func<float, std::string>(3.14f, s);});
GuncFunc([](std::string s){Func<std::string, int>(s, 42);});
選擇std::bind
或lambda表達式似乎是出於你的問題的範圍,但你可能會發現一些有用的東西here,there或this問題。
無論如何,很可能您需要lambdas,std::function,std::bind或variadic templates。
這當然可以在C++中完成。但是,你的問題有點不清楚。 「除了一行上的函數幾乎完全相同的幾個c函數」 - 這是完全不可分的。你能推斷並舉個例子嗎? –