當我寫作A::B::C為A一個類并B作為它的基類時,我假設我正在訪問C該基類中定義的B。當B它實際上不是A. B但是,當是模板時,顯然不是這樣,例如A::B<123>::C仍然給我,而且實際上是否是基礎B<123>::C似乎并不重要。我不知道為什么會有差異。它不解釋為訪問類的基類嗎?為什么不?它可以以某種方式重寫,以便它像訪問基類一樣解釋它嗎?B<123>AA::B<123>B<123>A
這是一個片段,詳細解釋了所做的事情,并附有解釋每個步驟的注釋:
// Here we show that we can't access a non-existent base of A
namespace WorksAsExpectedWithoutTemplates {
struct B
{
using C = void;
};
struct D
{
using C = void;
};
struct A: B
{
};
// Compiles as expected, B is a base of A, so Foo is B::C, aka void
using Foo = A::B::C;
// Doesn't compile, as expected, because D isn't a base of A, even though D::C
// exists
using Bar = A::D::C; // WE DON'T EXPECT THIS TO COMPILE, WHICH IS FINE
}
// Now we try the same thing with templates, and it doesn't behave the same way.
// Why?
namespace ActsDifferentlyWithTemplates {
template< int >
struct B
{
using C = void;
};
struct A: B< 42 >
{
};
// Compiles as expected, B< 42 > is a base of A, so Foo is B< 42 >::C, aka void
using Foo = A::B< 42 >::C;
// Compiles, Bar is B< 123 >::C, even though B< 123 > is not a base of A. Why
// does this behave differently than in the non-template case above? Can this be
// rewritten differently so that this wouldn't compile, same as in
// WorksAsExpectedWithoutTemplates, since B< 123 > isn't a base of A?
using Bar = A::B< 123 >::C; // WHY DOES THIS COMPILE? B< 123 > isn't a base of A
}
uj5u.com熱心網友回復:
template< int > struct B有一個注入類名 B,如果它緊跟在一個<. 該類struct A繼承了這一點。
所以,A::B< 123 >::C是一樣的B< 123 >::C,不是基類B< 42 >。例如:
template<int X>
struct B {
using C = char[X];
};
struct A : B<42> {};
using Foo = A::B<42>::C;
using Bar = A::B<123>::C;
using Baz = A::B::C; // (injected-class-name without template)
static_assert(sizeof(Foo) == 42);
static_assert(sizeof(Bar) == 123); // This is a different type
static_assert(sizeof(Baz) == 42);
這些情況實際上都不是“訪問基類”。它們都像任何其他成員型別別名/成員模板一樣從基類繼承注入的類名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459977.html
