특정 데이터 형식에 대해서만 제네릭 클래스에 대한 사용자 지정 메서드를 정의하는 데 관심이 있습니다. 나는 그것을 구현하는 좋은 방법이 무엇인지 확실하지 않다. 클래스 변수를 클래스 외부에 배치하면 클래스 변수에 액세스 할 수 없으므로 그렇게 할 수 없다고 생각합니다. 내가 클래스 안에 넣으면, 그것은 특정 타입이 아닌 모든 타입 T에서 작동하도록되어 있습니다. 나는 후자의 방법을 사용하기 위해 제네릭 버전을 정의하고 그 타입 만 입력으로 받아들이는 방법으로 코드를 만들 수 있었다.하지만 이것을 수행하는 데 더 좋은 방법이 있는가? 당신이 사용할 수있는, 또는C++ : 제네릭 클래스의 비 제너릭 메소드?
#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
}
: 아래
문제의 방법이 잘못된 유형으로 사용하는 경우 분명히#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
}
Meh, XY 문제. –
템플릿 전문화를 살펴보고 원하는 것을 찾을 수 있습니까? –
전문화 방법을 추가하는 유일한 방법은 전체 클래스를 전문화하는 것입니다. –