我想意识到一个接收STD ::相同参数的函数,然后称其为“如何”

I want to realize a function that receive the same parameters of std::bind and then call it, how?

本文关键字:函数 然后 参数 如何 意识到 STD 一个      更新时间:2023-10-16

我想实现的目标很简单,就像:

template<class Fn, class... Args> void ui::addExecutable(Fn&& fn, Args&&... args)
{
        va_list argptr;
        va_start(argptr, fn);
        ToBeExecuted.push_back(bind<Fn, Args...>(fn, argptr));
}

当我称呼它时:

    addExecutable(helloWorld, "ME!");

编译器说:

    undefined reference to `void cre::ui::addExecutable<void (&)(char const*), char const (&) [4]>(void (&)(char const*), char const (&) [4])'

我对模板不是很熟悉,并且做了一些Google,但没有线索。那么,如何正确地意识到"可添加"呢?谢谢!

如果您需要,所有源代码都在此。

您似乎在这里有多个问题:

  1. 您会获得链接器错误,因为将模板放入.cpp文件中。模板通常必须被内衬。

  2. 您混合模板,这是C 处理变量参数与C样式va_start/va_list的样式。那不起作用。在这种情况下,您应该坚持使用C 方式并删除功能中的前两行。

我猜你在调用中忘记了函数名称之后的参数列表:

模板返回型名称&lt;参数列表>(参数列表);

即。

addexecutable&lt; fn,class1,class2&gt;(helloworld," me!");

请参阅http://en.cppreference.com/w/cpp/language/function_template

如果您在C 中写作,则应该最好使用bind and function

等C 的东西

在这里为您提供一个示例:

#include <iostream>
#include <vector>
#include <functional>
// Collection of what you want to execute.
std::vector<std::function<void()>> vec;
// Add to the collection to be executed.
template<typename Fn, typename ...Args>
void addExecutable(Fn&& fn, Args&&... args)
{
    vec.push_back(
            std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...)
    );
}
// Execute everything in the collection.
void execute()
{
    for (auto& it: vec)
    {
        it();
    }
}
void helloWorld(std::string const& name)
{
    std::cout << "Hello " << name << std::endl;
}
void hello(std::string const& firstname, std::string const& lastname)
{
    std::cout << "Hello " << firstname << " " << lastname << std::endl;
}
int main()
{
    addExecutable(helloWorld, "Me");
    addExecutable(helloWorld, "You");
    addExecutable(hello, "John", "Smith");
    execute();
    return 0;
}
相关文章: