c ++模板从接口多重继承

时间:2013-01-31 16:43:03

标签: c++ templates virtual-inheritance

所以我有这个问题。

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

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 decleration。

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返回值和methods参数中的错误。 我认为这是一个模板冲突,但我真的不知道如何解决这个问题。

第一个错误:

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 ++进行编码并快速学习,但偶尔我会陷入困境并需要一些帮助。 我试图这样做的方式错了吗? 我是否需要声明第三个类型名称来解决这个冲突? (我认为它只会产生另一种冲突,因为这两种类型的类型相同)。

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

我试着让示例代码尽可能简单,以便在需要更多详细信息时解释我的问题。不要犹豫。

所有帮助都会非常有用。 感谢。

2 个答案:

答案 0 :(得分:2)

似乎第二类函数重载的返回值应为:

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

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

答案 1 :(得分:2)

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

#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...
    }

};