相关疑难解决方法(0)

"解包"一个元组来调用匹配的函数指针

我正在尝试存储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

251
推荐指数
6
解决办法
6万
查看次数

为每个可变参数模板参数和数组调用函数

所以我有一些类型X:

typedef ... X;
Run Code Online (Sandbox Code Playgroud)

和模板功能f:

class <typename T>
void f(X& x_out, const T& arg_in);
Run Code Online (Sandbox Code Playgroud)

然后是一个功能g:

void g(const X* x_array, size_t x_array_size);
Run Code Online (Sandbox Code Playgroud)

我需要编写一个variadic模板函数h来执行此操作:

template<typename... Args>
void h(Args... args)
{
    constexpr size_t nargs = sizeof...(args); // get number of args
    X x_array[nargs]; // create X array of that size

    for (int i = 0; i < nargs; i++) // foreach arg
        f(x_array[i], args[i]); // call f (doesn't work)

    g(x_array, nargs); // call g with …
Run Code Online (Sandbox Code Playgroud)

c++ templates variadic-templates c++11

25
推荐指数
3
解决办法
3万
查看次数

使用值列表初始化模板数组

在标准 C++ 中我们可以这样写:

int myArray[5] = {12, 54, 95, 1, 56};
Run Code Online (Sandbox Code Playgroud)

我想用模板写同样的东西:

Array<int, 5> myArray = {12, 54, 95, 1, 56};
Run Code Online (Sandbox Code Playgroud)

假如说

template <class Type, unsigned long N>
class Array
{
public:

    //! Default constructor
    Array();

    //! Destructor
    virtual ~Array();

    //! Used to get the item count
    //! @return the item count
    unsigned long getCount() const;

    //! Used to access to a reference on a specified item
    //! @param the item of the item to access
    //! @return a reference …
Run Code Online (Sandbox Code Playgroud)

c++ arrays templates

3
推荐指数
1
解决办法
2万
查看次数

如何使用构造函数的参数构造成员数组的每个元素

可能重复:
将std :: tuple转换为std :: array C++ 11

假设你有:

template<class T,int N>
struct A {
  A(const B& b): /* what comes here */ {}

  std::array<T,N> F;
};
Run Code Online (Sandbox Code Playgroud)

F[]在上面的例子中,我需要使用构造函数的参数构造每个元素b.这很棘手,因为参数可能不是可以是编译时常量的类型,例如int等等.

这不同于是否可以根据整数模板参数构造成员数组的元素?因为这里使用了用户定义的结构,因此我们需要它的运行时副本.

c++ templates c++11

3
推荐指数
1
解决办法
187
查看次数