小编use*_*164的帖子

有没有办法获得给定数量的输入,其中数字是在c ++的编译时由模板给出的?

例如,假设我创建了如下所示的类:

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或更高版本中有更好的方法,我也想知道.

c++ templates

9
推荐指数
1
解决办法
390
查看次数

使用 std::launder 以不正确的方式构造类或结构

假设您有一个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)

c++ stdlaunder

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

标签 统计

c++ ×2

stdlaunder ×1

templates ×1