我想意识到一个接收STD ::相同参数的函数,然后称其为“如何”
I want to realize a function that receive the same parameters of std::bind and then call it, how?
我想实现的目标很简单,就像:
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,但没有线索。那么,如何正确地意识到"可添加"呢?谢谢!
如果您需要,所有源代码都在此。
您似乎在这里有多个问题:
-
您会获得链接器错误,因为将模板放入
.cpp
文件中。模板通常必须被内衬。 -
您混合模板,这是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;
}
相关文章:
- 为什么我的递归函数按降序打印,然后按升序打印?
- 等待整个 omp 块完成,然后再调用第二个函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么 ComPtr 的函数返回不同的值,然后 &?
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 如何在C++中获取lua函数作为参数,然后调用它
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- 使用函数打开文件,然后让其他函数利用该文件?
- C++:将向量传递给函数,然后在main中调用函数.错过了什么
- 努力将指向成员函数的指针绑定到类模板的T成员,然后在槽中调用
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- C++大括号初始值设定项作为参数调用不同的构造函数,然后预期
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 如何在 LLVM 传递期间破坏然后解散函数?
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃
- 需要在调用函数然后检查errno之前清理errno
- 声明一个没有内容的函数;-然后是内容{}- c++