从接口的 C++ 模板多重继承

c++ template multiple inheritance from an interface

本文关键字:多重继承 C++ 接口      更新时间:2023-10-16

所以我有这个问题。

基本上我有一个模板化界面:

template <typename T, typename U>
class                    Iinterface
{
 public:
 virtual ~Iinterface()
 // A pure methode for the example that gives me the problem
 virtual std::vector<T>        myMethod(T, U) = 0;
};

暂时没问题。所以我声明了一个将从这个接口继承的类。

class                  firstclass : public Iinterface<std::string, int>
{
  // content doesnt matter. The problem is in second class inheritance.
  // here I just put the class so we can see how I inherited in 1st class.
};

现在 cpp 文件中的 myMethod 降级。

template <>
std::vector<std::string>        firstClass::iInterface<std::string, int>::myMethod(std::string a, int b)
 {
      // methods code
 }

到目前为止,我没有问题。在我的第二类中,我声明了 myMethod 函数,并且类型 T 与返回值相同,它给了我一个编译错误。

class                           secondClass : public IInterface<std::vector<std::string>, int>
{
  // class content
};

目前它编译,但是当我像这样声明myMethod时:

template <>
std::vector<std::string>                     secondClass::Iinterface<std::vector<std::string> a, int n>
{
  // methodes code
}

在这里,我收到一个错误,涉及 std::vector 返回值和方法参数中的返回值。我相信这是一个模板冲突,但我真的不知道如何解决这个问题。

第一个错误:

28 :template-id ‘_out<>’ for ‘std::vector<std::basic_string<char> > Iio<std::vector<std::basic_string<char> >, int>::_out(std::vector<std::basic_string<char> >, int)’ does not match any template declaration

第二个错误:

28 note: saw 1 ‘template<>’, need 2 for specializing a member function template

我仍在学习如何用 c++ 编码并快速学习,但偶尔我会卡住并需要一些帮助。我试图这样做的方式是错误的吗?我是否需要声明第三个类型名称来解决此冲突?(我以为它只会产生其他冲突,因为两个类型是同一类型)。

我知道我想做的事情可能不是最好的方法,但我仍在学习。

试图使示例代码尽可能简单,以解释我的问题,如果您需要更多详细信息,请随时询问。

所有的帮助都将非常有益。谢谢。

似乎第二个类函数重载的返回值应该是:

std::vector<std::vector<std::string> >

你用的是什么编译器,gcc在模板规范上给出了错误。

我认为作为一般规则,最好将模板化代码保存在 .h 文件中(代码必须在所有翻译单元中可用,因此如果您将其放入.cpp文件中,则不会编译它们,而是包含它们)。除了代码中的拼写错误(iInterface vs IInterface vs Iinterface等)之外,第二个类中的方法应该返回std::vector<std::vector<std::string> >。这是因为您的返回类型是 std::vector<T> 而您的 T 是 std::vector<std::string> 。下面的代码(代表interface.h)在mac os x上使用clang++ v 3.3编译得很好。

#include <string>
#include <vector>

template <typename T, typename U>
class Iinterface
{
public:
    virtual ~Iinterface();
    // A pure methode for the example that gives me the problem
    virtual std::vector<T> myMethod(T, U) = 0;
};
class firstclass : public Iinterface<std::string, int>
{
    // content doesnt matter. The problem is in second class inheritance.
    // here I just put the class so we can see how I inherited in 1st class.
    std::vector<std::string> myMethod(std::string a, int b)
    {
        // methods code
        // don't forget to return...
    }
};
class secondClass : public Iinterface<std::vector<std::string>, int>
{
    // class content
    std::vector<std::vector<std::string> > myMethod(std::vector<std::string> a, int n)
    {
        // methodes code
        // don't forget to return...
    }
};