2011-05-16 4 views
1

Windows에서 Solaris (Unix)로 일부 C++ 코드를 이식하려고합니다. 일부 템플릿 코드를 변경해야합니다. 나는 솔라리스의 컴파일러 CC를 사용하고 있습니다. g ++에는 같은 문제가 있습니다.명시 적 특수화 템플릿 다른 반환 유형이있는 클래스 멤버 함수

코드의 특정 부분에 약간의 문제가 있습니다. 그들은 다음과 같은 단순화 :

#include <exception> 
#include <cmath> 
#include <string> 
#include <iostream> 

// define the "not implement" error 
class tempException: public std::exception 
{ 
public: 
    virtual const char* what() const throw() 
    { 
     return "not been implemented!"; 
    } 
} nondeferr; 

// the template class 
template <typename T> 
class A 
{ 
public: 
    template <typename Val> 
    Val getValue(T t) { throw nondeferr; } 

    template<> 
    double getValue(T t) { return exp(1.5 * t); } //Specialize the getValue for double type. 
}; 

// test code 
int main() 
{ 
    try 
    { 
     A<int> testA; 

     std::cout << testA.getValue<double>(2) << std::endl; 
     std::cout << testA.getValue<std::string>(2) << std::endl; 
    } 
    catch (tempException& e) 
    { 
     std::cout << e.what() << std::endl; 
    } 

return 0; 
} 

는 UNIX에서이 샘플 코드를 컴파일하려면, 컴파일 오류가 A 급 범위에있을 수 없습니다 명시 적 전문성으로 나온다.

여기서 getValue 함수는 반환 유형과 만 다르므로 오버로드 방식을 사용하여 getValue 함수를 수정할 수 없습니다.

그리고 어떤 이유로, 간단한 템플릿 변수 T로 클래스 A를 두 개의 템플릿 변수 T와 함께 클래스 A로 변경하면 Val은 허용되지 않습니다. 이 기본 클래스를 사용하려고하면 많은 변화가 생깁니다.

해결책이 있는지 알고 싶습니까? 나는 현재 getValue 함수를 제거하고 getDoubleValue로 바꾸고 있지만 ... 너무 좋지 않습니다. 사람들을 위해


관심은 이제 클래스 A는 다음과 같습니다 사람 :

template <typename T> 
class A 
{ 
public: 
    // the Get Value we want 
    template <typename R> 
    R getValue(T t) { return get_value_impl<R>::apply(*this, t); } 

    // the general get value struct 
    template<typename R, typename = void> 
    struct get_value_impl 
    { 
     static R apply(A a, T t) { throw nondeferr; } 
    }; 

    // partial specialization, which is allowed in std C++ 
    template <typename S> 
    struct get_value_impl<double, S> 
    { 
     static double apply(A a, T t) { return exp(1.5 * t); } 
    }; 
}; 

뒤에 논리는 표준에서 허용되지 않습니다 명시 적 전문성이다. 그러나 부분 전문화는 허용됩니다. 화려한 솔루션에 대해 Anycorn에게 다시 한 번 감사드립니다.

답변

3
// the template class 
template <typename T> 
class A { 
    template<> 
    double getValue(T t) { return exp(1.5 * t); } 
}; 

표준으로 허용되지 않습니다.

가 할 : 주변의 클래스를 전문으로하지 않고 멤버 함수를 전문으로 할 수 없습니다

template <typename T> 
class A { 
    template<class R> 
    R getValue(T t) { return get_value_impl<double>::apply(*this, t); } 
    template<class R, class = void> 
    struct get_value_impl; // specialize this 
}; 
+0

솔루션 주셔서 감사합니다. 제안한 내용을 테스트 코드에 적용합니다. 그것은 잘 작동합니다 .... : :) – ygao

2

. Visual Studio에서는 이것을 확장자로 허용합니다.

관련 문제