다음을 통해 공유


종속적인 형식에 대한 이름 확인

템플릿 정의에서 정규화된 이름을 사용하여 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)있는 이름과 템플릿 인스턴스화의 컨텍스트를 모두 검사합니다. 다음 예제에서 템플릿은 기본 인스턴스화되므로 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는 "템플릿" 키워드(keyword) 명확하게 구분하기 위해 C++98/03/11 표준 규칙을 적용합니다. 다음 예제에서 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가 템플릿이 아니며 컴파일러에서 다음 " <"을 less-than으로 해석한다고 가정하기 때문에 명확성 규칙 준수가 필요합니다. C++에 Rebind가 템플릿이라는 것을 인지시켜 "<"을 꺾쇠로 올바르게 구문 분석할 수 있도록 해야 합니다.

참고 항목

이름 확인