c++ - 错误:没有匹配函数来调用 second::second,候选者是:second::second(

标签 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(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;
}

最佳答案

问题是你不能创建一个函数模板,它总是接受两个固定类型的参数,并根据模板参数返回不同类型的对象。原因是您不能专门化模板函数,只能重载它们,并且不能使重载函数仅在返回类型上有所不同。

你可以做的是使用 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

关于c++ - 错误:没有匹配函数来调用 second::second,候选者是:second::second(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26862380/

相关文章:

c++ - 在 Linux 上链接库时无法识别的选项 --kill-at

C# - 继承、覆盖

c++ - friend 类对象可以访问派生类对象上的基类私有(private)成员吗?

c++ - 为什么我不能从 C++ 中的模板化父类(super class)继承?

java接口(interface)和子类

c++ - 小写 null 在 C++ 中有效吗?

c++ - 如何使用模板函数作为 Boost::Unit-test 的自定义谓词

c++ - 使用 openGL 的多纹理映射

c++ - 如何将结构数组传递给C++中的函数

javascript - 自定义扩展 dijit/_TemplatedMixin 抛出 "Invalid template Error"