小编ron*_*ldo的帖子

为什么我们不能在 consteval 函数中使用编译时“变量”作为模板参数?

我正在测试这段代码(https://godbolt.org/z/fe6hhbeqW)...

// Returns the nth type in a parameter pack of types (ommited for clarity)
//   template <std::size_t N, typename...Ts>
//   nth_type{}

template <typename... Ts>
struct Typelist{
    template <typename T>
    consteval static std::size_t pos() noexcept { 
        for(std::size_t i{}; i < sizeof...(Ts); ++i) {
            using TN = nth_type_t<i, Ts...>;
            if (std::is_same_v<T, TN>) 
                return i;
        }
        return sizeof...(Ts);
    }
};
Run Code Online (Sandbox Code Playgroud)

我很困惑它不起作用。GCC 和 clang 同意i不作为常量表达式,因此他们拒绝让我将其作为模板参数传递。然而,i在编译时是清楚的,因此,根据我有限的理解,编译器使用它来实例化模板应该没有任何问题。

这有什么理由不起作用吗?将来有用吗?我已经用两个编译器的主干版本进行了测试,结果相同。

c++ templates metaprogramming c++20 consteval

8
推荐指数
2
解决办法
660
查看次数

无法使用声明中的初始化列表初始化const char*/string数组的向量

最初我开始尝试使用initilizer-list声明初始化const char*[3]的向量

vector<const char*[3]> v = { { "a", "b", "c" } };
Run Code Online (Sandbox Code Playgroud)

这给出了错误

matrix must be initialized with a brace-enclosed initializer
Run Code Online (Sandbox Code Playgroud)

我认为这可能是由于const char*,虽然看起来很奇怪,但却把它变成了字符串

vector<string[3]> v = { { "a", "b", "c" } };
Run Code Online (Sandbox Code Playgroud)

但错误仍然存​​在.我尝试了几种括号组合无济于事.实际上是否可以使用初始化列表初始化声明的结构?

c++ c++11

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

为什么new第一次分配1040个额外字节?

我正在创建这个简单的测试程序来演示使用标准new分配内存时对齐的工作方式...

#include <iostream>
#include <iomanip>
#include <cstdint>

//
// Print a reserved block: its asked size, its start address 
//       and the size of the previous reserved block
//
void print(uint16_t num, uint16_t size_asked, uint8_t* p) {
   static uint8_t* last = nullptr;

   std::cout << "BLOCK " << num << ":   ";
   std::cout << std::setfill('0') << std::setw(2) << size_asked << "b, "; 
   std::cout << std::hex << (void*)p;
   if (last != nullptr) {
      std::cout << ", " << std::dec << (uint32_t)(p - …
Run Code Online (Sandbox Code Playgroud)

c++ heap-memory memory-alignment new-operator

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