以下代码使用 C++17 在 Clang 15.0.7 和 GCC 12.2.0 编译器上成功编译:
template<typename T, std::size_t s = 0u>
struct A: std::false_type {};
template<typename T>
struct A<T, sizeof(T)>: std::true_type {};
static_assert(A<int, sizeof(int)>::value);
Run Code Online (Sandbox Code Playgroud)
但 MSVC 19.35.32215 失败并显示:
error C2753: 'A<T,sizeof(T)>': partial specialization cannot match argument list for primary template
error C2607: static assertion failed
Run Code Online (Sandbox Code Playgroud)
我已经有一个解决方法:
template<typename T, typename S>
struct B: std::false_type {};
template<typename T>
struct B<T, std::integral_constant<std::size_t, sizeof(T)>>: std::true_type {};
template<typename T, std::size_t s = 0u>
using A = B<T, std::integral_constant<std::size_t, s>>;
static_assert(A<int, sizeof(int)>::value); …Run Code Online (Sandbox Code Playgroud) c++ compiler-errors template-specialization visual-c++ c++17
C++ 标准是否允许在对象销毁之后但在释放之前使用对象提供的存储空间?
很明显,销毁常规对象后可以重用存储。但在下面的情况下,对象B为定义为模板参数的对象提供存储T,并在其自身构造期间在提供的存储中构造该对象。
此外,当对象被销毁时,提供的存储中的对象不会被销毁B,并且用于提供存储的数组的生命周期不会结束,因为它有一个没有效果的简单析构函数,这导致了一个问题:类型的对象A以或不结尾B。
#include <cstddef>
#include <iostream>
#include <memory>
#include <new>
struct A
{
int i = 23;
};
template<class T>
struct B
{
B()
{
// construct object T in the provided storage
new (&c) T;
}
// return a reference to the object in the provided storage
T & t()
{
return *std::launder(reinterpret_cast<T *>(&c));
}
// reserved storage
alignas(T) std::byte c[sizeof(T)];
};
int
main()
{ …Run Code Online (Sandbox Code Playgroud)