小编omi*_*nns的帖子

将struct转换为uint8_t的constexpr数组

我需要从constexpr结构中创建constexpr字节数组.

#include <array>

template<typename T>
constexpr std::array<uint8_t, sizeof(T)> o2ba(const T o) {
    return {};
}

struct A {
    int a;
};

int main() {
    constexpr A x{ 1 };
    constexpr auto y = o2ba(x); // y == { 0x01, 0x00, 0x00, 0x00 } for little endian
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我试图从联合中提取它:

template<typename T>
union U {
    T o;
    std::array<uint8_t, sizeof(T)> d;
};

template<typename T>
constexpr std::array<uint8_t, sizeof(T)> o2ba(const T o) {
    return U<T>{o}.d;
}
Run Code Online (Sandbox Code Playgroud)

但它在gcc和msvc编译器上都无法访问d而不是初始化的o成员.它在初始化非constexpr对象时起作用,如下所示.

int main() {
    constexpr A x{ …
Run Code Online (Sandbox Code Playgroud)

c++ arrays templates constexpr c++17

6
推荐指数
1
解决办法
401
查看次数

模板函数类型推导和返回类型

为什么atruebfalse?或者换句话说,为什么Tfoo1int const,但返回的类型foo2就是int

template<typename T>
constexpr bool foo1(T &) {
    return std::is_const<T>::value;
}

template<typename T>
T foo2(T &);

int main() {
    int const x = 0;
    constexpr bool a = foo1(x);
    constexpr bool b = std::is_const<decltype(foo2(x))>::value;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates template-argument-deduction

4
推荐指数
1
解决办法
206
查看次数

C++模板参数推导失败

为什么编译器可以使用以下代码推导出T:

#include <vector>

template<typename T>
void foo(T& t) {}

int main(void) {
    std::vector<uint8_t> vec = { 1,2,3 };
    foo(vec);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是这个代码失败了:

#include <vector>
#include <type_traits>

template<typename T>
void foo(typename std::enable_if<true, T>::type& t) {}

int main(void) {
    std::vector<uint8_t> vec = { 1,2,3 };
    foo(vec);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想使用第二个构造,在两个模板函数之间进行选择,基于传递的类方法存在.

c++ templates sfinae type-traits

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