共用方式為


名稱解析的相依型別

針對使用限定名稱 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.");
}

dx2zs2ee.collapse_all(zh-tw,VS.110).gifOutput

Name resolved by using typename keyword.

相依名稱搜尋、檢查來自兩個名稱的範本內容定義在下列範例中,這個內容中尋找 myFunction(char)—和樣板具現化的內容。在下列範例中,範本會在主要執行個體化,因此, MyNamespace::myFunction 從問題是可見的執行個體化 (Instantiation) 和選取做為這個較好的符合項目。如果 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);
}

dx2zs2ee.collapse_all(zh-tw,VS.110).gifOutput

Int MyNamespace::myFunction

dx2zs2ee.collapse_all(zh-tw,VS.110).gif釐清範本

Visual Studio 2012 中的 Visual C++ 執行區分 C++98/03/11 的標準規則與「template」關鍵字。在下列範例中, Visual C++ 2010 只接受非相容的線條和一致的行。 Visual Studio 2012 中的 Visual C++ 只接受一致的行。

#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 是範本,因此可以正確地解析「<」做為角括弧。

請參閱

參考

範本和名稱解析