C++ 错误:调用second::second没有匹配函数,候选函数为:second::second(

C++ 错误:调用second::second没有匹配函数,候选函数为:second::second(,c++,inheritance,C++,Inheritance,我需要根据模板化参数返回正确的类型。我得到的错误如下: 有人能建议一下这个问题的解决方案吗?提前谢谢 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(con

我需要根据模板化参数返回正确的类型。我得到的错误如下: 有人能建议一下这个问题的解决方案吗?提前谢谢

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&)
错误:对–second::second(const std::basic_string&)的调用没有匹配的函数
注:候选项为:second::second(const std::string&,const std::string&)
注:秒::秒(常数秒&)
代码如下:

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;
}
struct优先
{
公众:
常量字符串&str;
第一个(conststring&str):str(str){}
};
结构第二:公共第一
{
公众:
常量字符串&str2;
第二个(常量字符串和str1,常量字符串和str2):第一个(str1),str2(str2)
{    }
};
阶级基础
{
公众:
模板

内联T-fun(常量字符串&s1,常量字符串&s2);//{cout问题在于,您无法创建一个函数模板,该模板始终接受两个固定类型的参数,并根据模板参数返回不同类型的对象。原因是您无法专门化模板函数,只能重载它们,并且不能使重载函数仅按返回类型不同

您所能做的就是使用。这样,对于给定的模板参数,最多会出现一个函数:

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::fun
需要针对所有类型的
T
进行编译。您需要对
base::fun
进行专门化,以实现您的目标。
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);