2013-11-22 4 views
4

코드에서 템플릿 기능 언어 :C++ : 부분 특수화하는 방법 템플릿 클래스

template<typename Group> 
struct Vector3D { 
    Group x, y, z; 
    Vector3D(Group x, Group y, Group z) : x(x), y(y), z(z) { 
    } 
    template<int p> Group Norm() const; 
}; 

template<typename Group> template<int p> 
Group Vector3D<Group>::Norm() const { 
    return pow(pow(x, p) + pow(y, p) + pow(z, p), (1.0/p)); 
} 

/* 
template<typename Group> template<> 
Group Vector3D<Group>::Norm<2>() const { 
    return sqrt(x * x + y * y + z * z); 
}*/ 

주석으로 블록 VC11에서 컴파일에 실패 (vs2012)

이 사람이 무엇을 지적하는 데 도움이 수 partial에서 Norm 함수를 올바르게 처리 할 수 ​​있습니까?

답변

4

클래스 자체를 전문화하지 않고 회원 템플릿을 전문화 할 수 없습니다. 이를 위해서는 다른 메커니즘을 사용해야합니다. 예를 들어 int2type 템플릿을 사용하여 템플릿 인수를 오버로드 된 템플릿 세트에 인수로 전달할 수있는 유형으로 매핑 할 수 있습니다.

이 클래스 내에서 구현 될 수
template <int N> struct int2type {}; 

template <int N> void normImpl(int2type<N>*) { 
... 
} 
void normImpl(int2type<2>*) { 
... 
} 
template <int N> void norm() { 
    return normImpl(static_cast<int2type<N>*>(0)); 
} 

합니다 (int2type 외부가 좋은 유틸리티입니다 것을 제외) : 그것을 할 수있는 방법이 과도하게 단순화 스케치를 고려하십시오. 간접의 또 다른 수준의 도움이 시나리오 이러한 유형 중 일부의 경우와 마찬가지로

1

...

#include <iostream> 
#include <cmath> 
using namespace std; 

template <typename Group, int p> 
struct ApplyNorm 
{ 
    static Group apply(Group x, Group y, Group z) 
    { return pow(pow(x, p) + pow(y, p) + pow(z, p), (1.0/p)); } 
}; 

// Here specialize for 2 
template <typename Group> 
struct ApplyNorm<Group, 2> 
{ 
    static Group apply(Group x, Group y, Group z) 
    { 
     std::cout << "spec: " << std::endl; 
     return sqrt(x * x + y * y + z * z); 
    } 
}; 


template<typename Group> 
struct Vector3D { 
    Group x, y, z; 
    Vector3D(Group x, Group y, Group z) : x(x), y(y), z(z) { 
    } 
    template<int p> Group Norm() const; 
}; 

template<typename Group> template<int p> 
Group Vector3D<Group>::Norm() const { 
    return ApplyNorm<Group, p>::apply(x, y, z); // use the helper... 
} 

int main() { 
    // your code goes here 
    Vector3D<double> v(1., 2., 3.); 
    std::cout << v.Norm<1>() << std::endl; 
    std::cout << v.Norm<2>() << std::endl; 
    return 0; 
} 
+0

한 내 대답에 언급,하지만 다른 대안들 사이에서, A를 전달하지 않았나요 부분적으로 전문화 될 수있는 클래스 템플릿의 정적 멤버가 다른 좋은 옵션입니다. –