相依類型的名稱解析
用於 typename
範本定義中的限定名稱,告訴編譯器指定的限定名稱可識別類型。 如需詳細資訊,請參閱 typename 。
// template_name_resolution1.cpp
#include <stdio.h>
template <class T> class X
{
public:
void f(typename T::myType* mt) {}
};
class Yarg
{
public:
struct myType { };
};
int main()
{
X<Yarg> x;
x.f(new Yarg::myType());
printf("Name resolved by using typename keyword.");
}
Name resolved by using typename keyword.
相依名稱的名稱查閱會檢查範本定義內容中的名稱,如下列範例所示,此內容會尋找 myFunction(char)
此內容,以及範本具現化的內容。在下列範例中,範本會在 main 中具現化;因此, MyNamespace::myFunction
可從具現化點看到 ,並挑選為較佳的相符專案。 如果 MyNamespace::myFunction
已重新命名,則會改為呼叫 myFunction(char)
。
所有名稱都會做為相依名稱解析。 儘管如此,如果可能發生任何衝突,仍建議您使用完整限定名稱。
// template_name_resolution2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void myFunction(char)
{
cout << "Char myFunction" << endl;
}
template <class T> class Class1
{
public:
Class1(T i)
{
// If replaced with myFunction(1), myFunction(char)
// will be called
myFunction(i);
}
};
namespace MyNamespace
{
void myFunction(int)
{
cout << "Int MyNamespace::myFunction" << endl;
}
};
using namespace MyNamespace;
int main()
{
Class1<int>* c1 = new Class1<int>(100);
}
輸出
Int MyNamespace::myFunction
樣板去除混淆
Visual Studio 2012 會強制執行 C++98/03/11 標準規則,以厘清 「template」 關鍵字。 在下列範例中,Visual Studio 2010 會同時接受不符合規範的行和一致性行。 Visual Studio 2012 只接受符合的行。
#include <iostream>
#include <ostream>
#include <typeinfo>
using namespace std;
template <typename T> struct Allocator {
template <typename U> struct Rebind {
typedef Allocator<U> Other;
};
};
template <typename X, typename AY> struct Container {
#if defined(NONCONFORMANT)
typedef typename AY::Rebind<X>::Other AX; // nonconformant
#elif defined(CONFORMANT)
typedef typename AY::template Rebind<X>::Other AX; // conformant
#else
#error Define NONCONFORMANT or CONFORMANT.
#endif
};
int main() {
cout << typeid(Container<int, Allocator<float>>::AX).name() << endl;
}
遵循去除混淆規則是必要條件,因為根據預設,C++ 會假設 AY::Rebind
不是樣板,因此編譯器會將下列 "<
" 解譯為小於。 編譯器必須知道 Rebind
是樣板,才能將 "<
" 正確剖析為角括號。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應