相关疑难解决方法(0)

什么是'constexpr'有用?

我真的找不到任何用途.我的第一个想法是,我可以使用它来实现'按合同设计',而不使用像这样的宏:

struct S
{   
    S(constexpr int i) : S(i) { static_assert( i < 9, "i must be < 9" ); }

    S(int i); //external defintion

    char *pSomeMemory;
};
Run Code Online (Sandbox Code Playgroud)

但这不会编译.我想我们也可以使用它来引用同一变量,而不需要创建额外的内存,当我们想要避免get/setters时,为了使用户的一个成员的实例是只读的:

class S
{  
private:
    int _i;

public:
    const int & constexpr i = _i;
};
Run Code Online (Sandbox Code Playgroud)

但以上都没有实际编译过.有人可以告诉我为什么要引入这个关键字?

c++ compile-time language-lawyer c++11

15
推荐指数
3
解决办法
4076
查看次数

使用模板和内联进行C++元编程

是否值得编写如下代码来复制数组元素:

#include <iostream>
using namespace std;


template<int START, int N> 
struct Repeat { 
  static void copy (int * x, int * y) {
   x[START+N-1] = y[START+N-1];
   Repeat<START, N-1>::copy(x,y);
  }
};

template<int START> 
struct Repeat<START, 0> { 
  static void copy (int * x, int * y) {
   x[START] = y[START];
  }
};



int main () {


   int a[10];
   int b[10];

             // initialize
   for (int i=0; i<=9; i++) {
     b[i] = 113 + i;
     a[i] = 0;
   }

            // do the copy …
Run Code Online (Sandbox Code Playgroud)

c++ templates metaprogramming

5
推荐指数
1
解决办法
1333
查看次数