在模板,在那里,为什么我必须把typename和template上依赖的名字呢?究竟什么是依赖名称?我有以下代码:
template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> {
};
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion {
char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any …Run Code Online (Sandbox Code Playgroud) 假设我有一个包含两个数组成员的类,它们的元素类型相同但大小不同:
struct X
{
string a[2];
string b[3];
};
constexpr auto array_members = std::array{ &X::a, &X::b };
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为两个数组(具有不同的长度)具有不兼容的类型。
是否可以为两个成员指针分配一个通用类型?
我也尝试过,static_cast<string (X::*)[]>(&X::a)但由于数组类型不完整,因此也无法编译。
我无法使用,offsetof因为它需要使用非标准布局的类。
这可能是一种解决方法:
using array_type = decltype(X::b);
auto const array_members = std::array{
reinterpret_cast<array_type X::*>(&X::a), // cannot be constexpr
&X::b
};
Run Code Online (Sandbox Code Playgroud)
但是我担心调用未定义的行为。尽管我有信心在运行时没有超出范围的元素引用,但我们确实创建了指向的最后指针a,该指针给出的类型b似乎是界限内的。我不确定这是否违反规范。如果我可以使用constexpr与不兼容的工具,也会很方便reinterpret_cast。