我需要从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) 为什么a是true和b是false?或者换句话说,为什么T在foo1中int 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) 为什么编译器可以使用以下代码推导出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++ ×3
templates ×3
arrays ×1
c++17 ×1
constexpr ×1
sfinae ×1
template-argument-deduction ×1
type-traits ×1