문제

다음 코드 :

template <typename S, typename T>
struct foo {
   void bar();
};

template <typename T>
void foo <int, T>::bar() {
}

나에게 오류를 준다

invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'

(GCC를 사용하고 있습니다.) 부분 전문화에 대한 구문이 잘못 되었습니까? 두 번째 인수를 제거하면 다음과 같습니다.

template <typename S>
struct foo {
   void bar();
};

template <>
void foo <int>::bar() {
}

그런 다음 올바르게 컴파일됩니다.

도움이 되었습니까?

해결책

기능을 부분적으로 전문화 할 수 없습니다. 멤버 기능에서 그렇게하려면 전체 템플릿을 부분적으로 전문화해야합니다 (예, 자극적입니다). 대형 템플릿 클래스에서는 기능을 부분적으로 전문화하려면 해결 방법이 필요합니다. 아마도 템플릿 멤버 구조 (예 : template <typename U = T> struct Nested) 작동 할 것이다. 아니면 부분적으로 전문화되는 다른 템플릿에서 파생을 시도 할 수 있습니다 (사용하는 경우 작동합니다. this->member 표기법, 그렇지 않으면 컴파일러 오류가 발생합니다).

다른 팁

Coppro는 이미 두 가지 솔루션을 언급했지만 익명은 두 번째 솔루션을 설명했지만 첫 번째 솔루션을 이해하는 데 꽤 시간이 걸렸습니다. 어쩌면 다음 코드는이 사이트를 넘어서는 사람에게 도움이 될 것입니다. 예제 (숫자의 벡터/배열/단일 요소를 Datat로 전달한 다음 [] 또는 직접 액세스)는 물론 다소 고안되어 있지만 실제로 멤버 기능을 래핑하여 부분적으로 전문화하는 데 매우 가깝게 나오는 방법을 설명해야합니다. 부분적으로 전문화 된 수업에서.

/* The following circumvents the impossible partial specialization of 
a member function 
actualClass<dataT,numericalT,1>::access
as well as the non-nonsensical full specialisation of the possibly
very big actualClass. */

//helper:
template <typename dataT, typename numericalT, unsigned int dataDim>
class specialised{
public:
  numericalT& access(dataT& x, const unsigned int index){return x[index];}
};

//partial specialisation:
template <typename dataT, typename numericalT>
class specialised<dataT,numericalT,1>{
public:
  numericalT& access(dataT& x, const unsigned int index){return x;}
};

//your actual class:
template <typename dataT, typename numericalT, unsigned int dataDim>
class actualClass{
private:
  dataT x;
  specialised<dataT,numericalT,dataDim> accessor;
public:
  //... for(int i=0;i<dataDim;++i) ...accessor.access(x,i) ...
};

생성자를 부분적으로 전문화 해야하는 경우 다음과 같은 것을 시도 할 수 있습니다.

template <class T, int N>
struct thingBase
{
    //Data members and other stuff.
};

template <class T, int N> struct thing : thingBase<T, N> {};

template <class T> struct thing<T, 42> : thingBase<T, 42>
{
    thing(T * param1, wchar_t * param2)
    {
        //Special construction if N equals 42.
    }
};

참고 : 이것은 내가하고있는 일에서 익명으로 만들어졌습니다. 많은 멤버가있는 템플릿 클래스가있을 때이를 사용할 수 있으며 함수를 추가하려고합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top