특정 데이터 유형에 대해서만 제네릭 클래스에 대한 사용자 지정 메서드를 정의하는 데 관심이 있습니다. 그것을 구현하는 좋은 방법이 무엇인지 잘 모르겠습니다. 클래스 외부에 배치하면 클래스 변수에 액세스 할 수 없으므로 결코 그런 식으로 작동하지 않을 것 같습니다. 클래스 안에 배치하면 특정 유형뿐만 아니라 모든 유형 T에서 작동한다는 의미입니다. 제네릭 버전을 정의하고 해당 유형 만 관심있는 입력으로 전송하여 후자의 방식으로 코드를 작동 할 수 있었지만이를 수행하는 더 깔끔한 방법이 있습니까?
다음은 명확하게하는 몇 가지 코드입니다.
#include<iostream>
#include<string>
using namespace std;
template<typename T>
class abc
{
public:
void myvoid();
};
template<typename string>
void abc<string>::myvoid()
{
cout<<"This portion should execute only if an instance of class is called with a string parameter" ;
}
int main()
{
abc<int> int1;
abc<string> string1;
string1.myvoid(); //should work good
int1.myvoid(); //shouldnt execute myvoid
}
static_assert
문제의 메서드가 잘못된 유형으로 사용되는 경우 컴파일을 방지 하는 데 사용할 수 있습니다 .
#include <type_traits> // for std::is_same
template <typename T>
struct Foo
{
void foo() const {}
void bar() const
{
static_assert(std::is_same<T, int>::value, "T is not int");
}
};
int main()
{
Foo<double> fd;
fd.foo(); // OK
//fd.bar(); // ERROR: bar() only works with Foo<int>
Foo<int> fi;
fi.foo(); // OK
fi.bar(); // OK
}
또는를 사용 SFINAE
하여 해당 메서드가 존재하는 유형을 제어 할 수 있습니다.
template <typename T>
class Foo
{
public:
void foo() const {}
template<typename T2 = T,
typename = typename std::enable_if<std::is_same<T, int>::value>::type>
void bar() {}
};
이 관련 질문을 참조하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다