我正在尝试存储std::tuple不同数量的值,这些值稍后将用作调用与存储类型匹配的函数指针的参数.
我创建了一个简化的示例,显示了我正在努力解决的问题:
#include <iostream>
#include <tuple>
void f(int a, double b, void* c) {
std::cout << a << ":" << b << ":" << c << std::endl;
}
template <typename ...Args>
struct save_it_for_later {
std::tuple<Args...> params;
void (*func)(Args...);
void delayed_dispatch() {
// How can I "unpack" params to call func?
func(std::get<0>(params), std::get<1>(params), std::get<2>(params));
// But I *really* don't want to write 20 versions of dispatch so I'd rather
// write something like:
func(params...); // Not legal
}
}; …Run Code Online (Sandbox Code Playgroud) c++ function-pointers variadic-templates c++11 iterable-unpacking
是否可以以某种方式存储参数包供以后使用?
template <typename... T>
class Action {
private:
std::function<void(T...)> f;
T... args; // <--- something like this
public:
Action(std::function<void(T...)> f, T... args) : f(f), args(args) {}
void act(){
f(args); // <--- such that this will be possible
}
}
Run Code Online (Sandbox Code Playgroud)
然后是:
void main(){
Action<int,int> add([](int x, int y){std::cout << (x+y);}, 3, 4);
//...
add.act();
}
Run Code Online (Sandbox Code Playgroud) 当我偶然发现这个问题时,我正在尝试使用C++ 0x可变参数模板:
template < typename ...Args >
struct identities
{
typedef Args type; //compile error: "parameter packs not expanded with '...'
};
//The following code just shows an example of potential use, but has no relation
//with what I am actually trying to achieve.
template < typename T >
struct convert_in_tuple
{
typedef std::tuple< typename T::type... > type;
};
typedef convert_in_tuple< identities< int, float > >::type int_float_tuple;
Run Code Online (Sandbox Code Playgroud)
当我尝试输入模板参数包时,GCC 4.5.0给出了一个错误.
基本上,我想将参数包"存储"在typedef中,而无需解压缩.可能吗?如果没有,是否有一些理由不允许这样做?
在C++ 11模板中,有没有办法将元组用作(可能是模板)函数的各个args?
示例:
假设我有此功能:
void foo(int a, int b)
{
}
Run Code Online (Sandbox Code Playgroud)
我有元组auto bar = std::make_tuple(1, 2).
我可以用它以foo(1, 2)一种模板的方式打电话吗?
我的意思并不简单,foo(std::get<0>(bar), std::get<1>(bar))因为我想在一个不知道args数量的模板中这样做.
更完整的例子:
template<typename Func, typename... Args>
void caller(Func func, Args... args)
{
auto argtuple = std::make_tuple(args...);
do_stuff_with_tuple(argtuple);
func(insert_magic_here(argtuple)); // <-- this is the hard part
}
Run Code Online (Sandbox Code Playgroud)
我应该注意,我宁愿不创建一个适用于一个arg的模板,另一个适用于两个arg的模板等等...
我正在尝试创建一个通用的包装器函数,它将函数作为模板参数,并使用与该函数相同的参数作为其参数.例如:
template <typename F, F func>
/* return type of F */ wrapper(Ts... Args /* not sure how to get Ts*/)
{
// do stuff
auto ret = F(std::forward<Ts>(args)...);
// do some other stuff
return ret;
}
Run Code Online (Sandbox Code Playgroud)
解决方案需要可以转换为具有相同类型的函数指针,func以便我可以将其传递给C api.换句话说,解决方案需要是一个函数而不是一个函数对象.最重要的是,我需要能够在包装函数中完成工作.
如果内联评论不清楚,我希望能够做如下的事情:
struct c_api_interface {
int (*func_a)(int, int);
int (*func_b)(char, char, char);
};
int foo(int a, int b)
{
return a + b;
}
int bar(char a, char b, char c)
{
return a + b * c; …Run Code Online (Sandbox Code Playgroud)