例如,假设我创建了如下所示的类:
template <unsigned int INPUT_SIZE>
class A{
public:
int operator()(int input, ...){ // get INPUT_SIZE-many inputs
// return sum;
}
};
Run Code Online (Sandbox Code Playgroud)
我想获得与INPUT_SIZE一样多的输入,而不是更多或更少.我怎样才能做到这一点?
另外,我使用的是c ++ 11,但如果在c ++ 14或更高版本中有更好的方法,我也想知道.
假设您有一个structwith 元素,您不想(不能)在初始化阶段初始化它,但它不是默认可初始化的。我想出了一种使用方法std::launder:为结构分配一个空间,然后使用洗衣槽在正确的位置分配一个值。例如,
#include <cassert>
#include <cstddef>
#include <iostream>
#include <new>
struct T {
int t;
};
struct S {
int x;
T t;
S() = delete;
S(int x) : x(x) {}
};
int main() {
alignas(S) std::byte storage[sizeof(S)];
S s0(42);
// 0. I believe that the commented line is dangerous, although it compiles well.
// *std::launder(reinterpret_cast<S*>(storage)) = s0;
S *ps = std::launder(reinterpret_cast<S*>(storage));
ps->x = 42;
ps->t = T{};
{ // 1. Is this safe?
S …Run Code Online (Sandbox Code Playgroud)