相关疑难解决方法(0)

你如何迭代std :: tuple的元素?

如何迭代元组(使用C++ 11)?我尝试了以下方法:

for(int i=0; i<std::tuple_size<T...>::value; ++i) 
  std::get<i>(my_tuple).do_sth();
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

错误1:抱歉,未实现:无法将"Listener ..."扩展为固定长度的参数列表.
错误2:我不能出现在常量表达式中.

那么,我如何正确迭代元组的元素?

c++ iteration template-meta-programming c++11 stdtuple

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

在运行时指定模板参数

考虑以下模板类

class MyClassInterface {
public:
  virtual double foo(double) = 0;
}

class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
  double foo(double a) {
    // complex computation dependent on P1, P2, P3
  }
  // more methods and fields (dependent on P1, P2, P3)
}
Run Code Online (Sandbox Code Playgroud)

模板参数P1,P2,P3是在限制范围就像从0一些固定值n固定在编译时.

现在我想建立一个像"工厂"的方法

MyClassInterface* Factor(int p1, int p2, int p3) {
  return new MyClass<p1,p2,p3>(); // <- how to do this?
}
Run Code Online (Sandbox Code Playgroud)

问题是如何在模板参数仅在运行时知道时如何实现模板类的构造.对于具有非常大的域(如双)的模板参数,同样可能吗?如果可能的解决方案可扩展到使用更多模板参数,请另请考虑.

c++ templates

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

是否有自动noexcept说明符?

我听说noexcept关键字更像是'它永远不应该抛出异常',而不是'它没有'.

我不认为使用noexcept关键字是好的,如果我不确定它是否会抛出异常,但noexcept关键字有时与移动构造函数中的性能有关.

所以我尝试使用noexcept限定符,但如果它在定义中有多个语句就变得更难,它变成了一种复制和粘贴的东西.

template <class T>
void f(T&& t)
    noexcept(noexcept(statement_1) &&
             noexcept(statement_2) &&
             noexcept(statement_3) &&
             noexcept(statement_4) &&
             noexcept(statement_5))
{
    statement_1;
    statement_2;
    statement_3;
    statement_4;
    statement_5;
}
Run Code Online (Sandbox Code Playgroud)

我认为编译器可以判断一个函数的定义是否包含非抛出语句,因此noexcept如果有一个类似的表达式会更容易使用noexcept(auto),但似乎标准中没有这样的东西.

有没有办法简化noexcept表达式?

c++ noexcept c++11 c++14

26
推荐指数
1
解决办法
1284
查看次数

当我在编译时不知道时,如何从std :: tuple获取第i个元素?

我有一个i类型的变量std::size_t和一个类型的元组std::tuple.我想得到i元组的-th元素.我试过这个:

// bindings... is of type const T&...
auto bindings_tuple = std::make_tuple(bindings...);
auto binding = std::tuple_element<i, const T&...>(bindings_tuple);
Run Code Online (Sandbox Code Playgroud)

但我得到这个编译错误,说第一个模板参数必须是一个整数常量表达式:

错误:类型' std::size_t'(又名' unsigned long')的非类型模板参数不是整型常量表达式

是否有可能获得i元组的-th元素,以及如何做到这一点?


如果可能的话,我想在不使用提升的情况下这样做.

c++ tuples c++11

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

if和switch语句的函数数组的性能

我正在编写一个非常重要的性能代码部分,我有一个关于用函数指针数组替换case语句(或if语句)的疯狂想法.

让我来证明一下; 这是正常版本:

while(statement)
{
    /* 'option' changes on every iteration */

    switch(option)
    {
        case 0: /* simple task */ break;
        case 1: /* simple task */ break;
        case 2: /* simple task */ break;
        case 3: /* simple task */ break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里是"回调函数"版本:

void task0(void) {
    /* simple task */
}

void task1(void) {
    /* simple task */
}

void task2(void) {
    /* simple task */
}

void task3(void) {
    /* simple task */
}

void (*task[4]) (void); …
Run Code Online (Sandbox Code Playgroud)

c optimization if-statement callback switch-statement

15
推荐指数
1
解决办法
8758
查看次数