C++ 为接受函数指针作为多种函数类型参数的函数创建模板函数

C++ 为接受函数指针作为多种函数类型参数的函数创建模板函数,c++,templates,overloading,function-pointers,function-declaration,C++,Templates,Overloading,Function Pointers,Function Declaration,我有几个c函数,除了一行上的函数外,它们做的事情几乎完全相同。我想用一个函数替换所有这些函数,该函数可以作为该行的函数指针传递: Func1(type parameter); Func2(type1 parameter1,type2 parameter2); FuncFunc(FunctionPointer functionPointer){ funcVar; ... functionPointer(funcVar,....); ... } int main

我有几个c函数,除了一行上的函数外,它们做的事情几乎完全相同。我想用一个函数替换所有这些函数,该函数可以作为该行的函数指针传递:

Func1(type parameter);

Func2(type1 parameter1,type2 parameter2);

FuncFunc(FunctionPointer functionPointer){
    funcVar;
    ...
    functionPointer(funcVar,....);
    ...
}

int main(){
    FuncFunc(Func1);

    FuncFunc(Func2(,type2Object));
}

<> P> >我可以在C++中这样做吗?

< p>你不清楚你在试图达到什么,但是这里有一个例子,你的代码可以如何翻译成有效C++。首先,让我们使用最大数量的参数定义您的
Func

template<typename T1, typename T2>
void Func(T1 par1, T2 par2) {
        std::cout << par1 << " " << par2 << std::endl;
}
或更易于使用的变体:

template<typename F>
void GuncFunc(const F& fPtr) {
        std::string funcVar = "Foo!";
        fPtr(funcVar);
}
GuncFunc

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;
// 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
GuncFunc(std::bind(Func,3.14f,std::占位符::_1));
GuncFunc(std::bind(Func,std::占位符::_1,42));
//或使用lambdas:
GuncFunc([](std::string s){Func(3.14f,s);});
GuncFunc([](std::string s){Func(s,42);});
选择
std::bind
或lambdas似乎超出了您的问题范围,但您可能会发现一些有用的东西,或者存在疑问


无论如何,你很可能需要,或者./P>这当然可以在C++中完成。不过,你的问题有点不清楚。“除了一行上的函数外,几个c函数做的事情几乎完全相同”——这是完全不可解析的。你能推断并给出一个例子吗?你也可以使用lambdas而不是

std::bind
// 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);});