2014-11-11 3 views
1

templatized 인수에 따라 적절한 형식을 반환해야합니다. 아래 오류가 발생합니다. 누군가 제안 할 수 있습니까? ? 사전에 이에 대한 해결책은 감사오류 : 두 번째 :: 두 번째 호출에 대한 일치하는 함수가 없습니다. 두 번째 :: 초 (

error: no matching function for call to âsecond::second(const std::basic_string<char, 
std::char_traits<char>, std::allocator<char> >&)â 
note: candidates are: second::second(const std::string&, const std::string&) 
note:     second::second(const second&) 

코드는 다음과 같습니다 :.

struct first 
{ 
public: 
    const string &str; 
    first(const string & str) : str(str)  { } 
}; 

struct second : public first 
{ 
public: 
    const string &str2; 
    second(const string &str1, const string &str2) : first(str1), str2(str2) 
    { } 
}; 

class base 
{ 
public: 
    template<class T> 
    inline T fun(const string &s1, const string &s2);//  { cout<<" T = "<<a; } 
}; 

template<class T> 
inline T base::fun(const string &s1, const string &s2) 
{ 
    if(1) 
     return T(s1); 
    else 
     return T(s1, s2); 
} 


int main() 
{ 
    string a = "a"; 
    string bb = "b"; 
    base b; 
    b.fun<first>(a, bb); 
    b.fun<second>(a, bb); 
    return 0; 
} 
+0

기능'기본 :: fun' 모든 유형의 'T'에 대해 컴파일 할 수 있어야합니다. 당신이하고 싶은 것을 성취하기 위해서는'base :: fun'를 전문화해야 할 것입니다. – Niall

답변

2

문제는 항상 고정 된 형태의 두 개의 인수를 받아들이는 함수 템플릿을 생성 할 수 있으며, 템플릿 매개 변수에 따라 다른 유형의 객체를 반환합니다. 템플릿 함수를 특수화 할 수 없으며, 오버로드 된 함수 만 반환 유형별로 다르게 만들 수는 없습니다.

SFINAE을 사용하면됩니다. 최대 하나 개의 기능은 주어진 템플릿 매개 변수에 대한 존재합니다이 방법은 :

class base { 
public: 
    template<typename T, typename = typename std::enable_if<std::is_same<T, first>::value>::type> 
    first fun(const string &s1, const string &s2) { 
     return first(s1); 
    } 

    template<typename T, typename = typename std::enable_if<std::is_same<T, second>::value>::type> 
    second fun(const string &s1, const string &s2) { 
     return second(s1, s2); 
    } 
}; 

은 또한 당신은 템플릿 base을하고 전문 수 있습니다

template<typename T> class base; 

template<> class base<first> { 
public: 
    static first fun(const string &s1, const string &s2) { 
     return first(s1); 
    } 
}; 

template<> class base<second> { 
public: 
    static second fun(const string &s1, const string &s2) { 
     return second(s1, s2); 
    } 
}; 

base<first>::fun(a, bb); 
base<second>::fun(a, bb); 

Demo

관련 문제