1
다음 코드에서 런타임 값을 기반으로 특정 함수 템플릿 인스턴스를 호출하려고한다고 가정합니다. 여러 함수에 대해이 작업을 여러 번해야 할 필요가 있으므로 함수 (test)에 조건문을 래핑하고 함수 템플릿 "func"을 전달하려고했습니다. 그래서 난과 같이 ... 구조체에서 "FUNC"템플릿을 포장 :함수 템플릿을 임의의 인수 목록이있는 함수 템플릿에 전달
#include<iostream>
#include<typeinfo>
struct wrapper
{
public:
template< typename T >
static int funcT(int a)
{
std::cout<<"your func type and value is "<<typeid(T).name()<<" "<<a<<std::endl;
}
static int func(int a)
{
std::cout<<"your func type and value is "<<typeid(int).name()<<" "<<a<<std::endl;
}
};
enum class TypeIDs
{
real8_id,
int4_id
};
template< typename WRAPPER, typename RTYPE, typename...ArgsF >
static RTYPE test(const TypeIDs type, ArgsF... args)
{
RTYPE junk = WRAPPER::func(args...);
RTYPE rval;
switch(type)
{
case(TypeIDs::real8_id):
{
rval = typename WRAPPER::funcT<double>(args...);
break;
}
case(TypeIDs::int4_id):
{
rval = WRAPPER::funcT<int>(args...);
break;
}
}
return rval;
}
int main()
{
wrapper::funcT<double>(1);
test<wrapper,int>(TypeIDs::real8_id, 1);
}
컴파일 결과 : 그래서
g++48 -std=c++11 templatesandfunctions.cpp
templatesandfunctions.cpp: In function 'RTYPE test(TypeIDs, ArgsF ...)':
templatesandfunctions.cpp:47:37: error: expected '(' before '<' token
rval = typename WRAPPER::funcT<double>(args...);
^
templatesandfunctions.cpp:47:38: error: expected primary-expression before 'double'
rval = typename WRAPPER::funcT<double>(args...);
^
templatesandfunctions.cpp:47:38: error: expected ';' before 'double'
templatesandfunctions.cpp:52:29: error: expected primary-expression before 'int'
rval = WRAPPER::funcT<int>(args...);
^
templatesandfunctions.cpp:52:29: error: expected ';' before 'int'
: 예상대로 주요 컴파일 ... 호출
wrapper::funcT<double>(1)
. 전화
test<wrapper,int>(TypeIDs::real8_id, 1);"
컴파일 않는 비 템플릿 기능
WRAPPER::func(args...);
에서
.
그러나 템플릿 기능은 typename 지정자를 사용하거나 사용하지 않고 컴파일하지 않습니다.
WRAPPER::funcT<double>(args…);
typename WRAPPER::funcT<double>(args…);
이것이 작동하지 않는 이유는 누구나 알고 있으며 어떻게 작동하게 할 수 있습니까?
감사합니다. 합니다 (typename
및 생략)가 종속 템플릿 이름 다루고있어 컴파일러를 알려주는
잘 작동합니다! 고마워. 나는 그런 요구조차 본 적이 없다! 한 가지 질문은 괜찮 으면 ... 왜 주 템플릿에서 템플릿 호출이 작동합니까? 컴파일러가 그것에 대해 엄격 해지면 작동하지 않아야하는 것처럼 보입니다. – doc07b5
@ doc07b5가 업데이트되었습니다. 컴파일러는 그것을 파싱 할 수 있다는 것을 부끄러워합니다. 참조 : http://en.cppreference.com/w/cpp/language/dependent_name 섹션 : "종속 이름에 대한 템플릿 모호성 제거기" – justin