c++ 함수 템플릿 파라미터 타입추론에 대한 궁금증

조회수 1126회
#include <type_traits>

class A{};

template< typename T > struct is_allowed 
{ 
    enum { value = false };
};

template<>  struct is_allowed<A>
{ 
    enum { value = true };  
};


template< typename T >
void f( std::enable_if_t< is_allowed<T>::value , T >* Parent )
{

}

int main()
{
    A a;
    f( &a );

    return 0;
}


간단한 함수 템플릿이 있는데요. f 함수는 왜 A 클래스에 대한 타입추론을 하지 못한다고 할까요? 개발 환경은 VC2017 입니다.

에러 메시지 : error C2783: 'void f(enable_if<_Test,T>::type *)': could not deduce template argument for 'T'

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • http://en.cppreference.com/w/cpp/language/template_argument_deduction#Non-deduced_contexts

    에 다음과 같은 내용이 있습니다.

    In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

    질문 하신 내용에서 P 는 std::enable_if< is_allowed<T>::value , T >::type* 가 됩니다.

    여기서 In the following cases::type 과 같이 :: 를 이용한 내부 이름에 접근 하는 경우가 있습니다.

    즉, P 로 ::type 을 사용하였기 때문에 non-deduced contexts 의 경우에 포함되고, 이는 타입 추론을 하지 않는 다는 규칙 때문에 말씀하신 오류가 발생한 것입니다.

    std::enable_if< is_allowed<T>::value , T >::type* 이 추론이 되지 않으므로, 이를 A* 로 치환 되게 하려면은 T 가 추론될 수 있게 수정해 줄 필요가 있습니다.

    따라서 T 를 간단하게 추론할 수 있게 아래와 같이 변경할 수 있습니다.

    template< typename T >
    void f( T* Parent, std::enable_if_t< is_allowed<T>::value , T >* = 0 )
    {
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)