我正在测试这段代码(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在编译时是清楚的,因此,根据我有限的理解,编译器使用它来实例化模板应该没有任何问题。
这有什么理由不起作用吗?将来有用吗?我已经用两个编译器的主干版本进行了测试,结果相同。
最初我开始尝试使用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)
但错误仍然存在.我尝试了几种括号组合无济于事.实际上是否可以使用初始化列表初始化声明的结构?
我正在创建这个简单的测试程序来演示使用标准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)