템플릿 클래스를 만들고 싶고 템플릿 매개 변수의 typeid에 따라 다른 동작을 수행한다면 어떻게 코딩해야합니까?템플릿 클래스의 여러 템플릿 매개 변수에 대해 서로 다른 작업을 수행하려면 어떻게해야합니까?
예를 들어 int 또는 string 여부에 따라 구성원 필드 데이터를 초기화하려는 템플릿 클래스가 있습니다.
#include <string>
template <class T>
class A
{
private:
T data;
public:
A();
};
// Implementation of constructor
template <class T>
A<T>::A()
{
if (typeid(T) == typeid(int))
{
data = 1;
}
else if (typeid(T) == typeid(std::string))
{
data = "one";
}
else
{
throw runtime_error("Choose type int or string");
}
}
이 코드는 다음 주 파일과 함께 컴파일되지 않습니다.
#include "stdafx.h"
#include "A.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
A<int> one;
return 0;
}
오류 : 오류 C2440는 '='실제로 다른-IF 명령문의 int 심지어를 검사 코드 수단 '내부'에 '[2] CONST 문자'로 변환 할 수없는 코드의 해당 부분에 도달 할 수는 없지만
다음 예제에서는 (Perform different methods based on template variable type), 다음 A.h 파일을 시도했지만 A.obj에 A (void)가 이미 정의되어 있다는 링커 오류가 몇 가지 있습니다.
#include <string>
template <class T>
class A
{
private:
T data;
public:
A();
~A();
};
// Implementation of constructor
template <>
A<int>::A()
{
data = 1;
}
template <>
A<std::string>::A()
{
data = "one";
}
누구든지이 코드를 실행하는 방법을 알고 있습니까? 또한 템플릿 클래스에서 이와 같은 if-else 문을 사용하면 템플릿에서 전원이 제거 될 수 있다는 것을 알고 있습니다. 이 코드를 작성하는 더 좋은 방법이 있습니까?
편집 :
#pragma once
#include <string>
// Class definition
template <class T>
class A
{
public:
A();
~A();
private:
T data;
};
// Implementation of initialization
template < class T >
struct initial_data
{
static T data() { throw runtime_error("Choose type int or string"); }
};
template <>
struct initial_data<int>
{
static int data() { return 1; }
};
template <>
struct initial_data<std::string>
{
static std::string data() { return "one"; }
};
// Definition of constructor
template <class T>
A<T>::A()
: data(initial_data<T>::data())
{
}
다음과 같은 주요 : : 지금 얻을
#include "stdafx.h"
#include "A.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
A<int> ione;
return 0;
}
링커 오류는 다음과 같습니다 스텐 (아래), 지금 다음 아 파일이와 논의 후 테스트 템플릿 4.obj : 오류 LNK2019 : 함수 _wmain에서 참조되는 확인되지 않은 외부 기호 "public : __thiscall A :: ~ A (void)"(?? 1? $ A @ H @@ QAE @ XZ)
1)'_tmain' 쓰레기와 친구들을 사용하지 마십시오. 2) 템플릿과 함께'typeid'를 사용하는 것은 무엇입니까? 'int :: operator = (const char *)'가 없으므로 코드는 단순히'T = int'에 대해 컴파일되지 않습니다 ... 3) 컴파일 에러에 대한 테스트 케이스를 참조하십시오. – Griwes
두 번째 예제로 수행 한 템플릿 전문화는 IMHO로 이동하는 방법입니다. 헤더 파일에 포함 가드를 추가 했습니까? 링커 오류에서 그것은 당신처럼 보이지 않습니다. – Naveen
나는 이것을 위해 SFINAE를 사용할 수 있다고 생각합니다. 'enable_if'와'is_same'을 사용하면 템플릿 params를 기반으로 다른 멤버 함수를 가질 수 있습니다. – jrok