8

编辑:根据一些评论,简单的意思是a)代码更少,b)易于维护,c)很难出错。

编辑#2:此外,如果确实简化了InterfaceImpl.

目前,我知道的唯一方法是让实现者定义抽象方法并将调用委托给目标基类型的方法。例子:

#include <iostream>
#include <memory>

class Interface
{
public:
    virtual void method1() = 0;
    virtual void method2(int x) = 0;
};

class MethodOneImpl
{
 private:
    void method1(int x)
    { std::cout << "MethodOneImpl::method1() " << x << std::endl; }

 public:
    void method1() { method1(0); }
};

class MethodTwoImpl
{
 public:
    void myFunc(int x)
    { std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
};

class InterfaceImpl : public Interface
                    , private MethodOneImpl
                    , private MethodTwoImpl
{
public:    
    virtual void method1() { MethodOneImpl::method1(); }
    virtual void method2(int x) { MethodTwoImpl::myFunc(x); }
};

int main()
{
    std::unique_ptr<Interface> inf;
    inf.reset(new InterfaceImpl);
    inf->method1();
    inf->method2(0);

    // This should be disallowed!
    // std::unique_ptr<MethodOneImpl> moi;
    // moi.reset(new InterfaceImpl);
}

起初,我认为这也许可以解决问题:

class InterfaceImpl : public Interface
                    , private MethodOneImpl
                    , private MethodTwoImpl
{
public:    
    using MethodOneImpl::method1;
    // Obviously this wouldn't work as the method names don't match.
    //using MethodTwoImpl::??? 
};

第一个 using 语句将使这两个MethodOneImpl::method1方法都公开,但它实际上不履行与 的约定Interface,并且它修改了 的可访问性MethodOneImpl::method1(int)。显然我们不能使用这个解决方案,method2因为名称不匹配。

FWIW,我有我认为的解决方案,但它根本不是标准的一部分(换句话说,它不会编译)。我正在考虑向 C++ 委员会提出建议;如果有人有任何建议,我将不胜感激下面的任何评论(但请不要将建议作为答案提交)。

4

5 回答 5

4

另一种选择(至少如果使用 MS VC++)是使用虚拟继承:

struct MyInterface
{
    virtual void Method1() = 0;
    virtual void Method2() = 0;
};

class Method1Impl : public virtual MyInterface
{
    virtual void Method1() { _tprintf( _T("Method1\n") ); }
};

class Method2Impl : public virtual MyInterface
{
    virtual void Method2() { _tprintf( _T("Method2\n") ); }
};

class InterfaceImpl : public virtual MyInterface,
                      private Method1Impl,
                      private Method2Impl
{
};

void TestWeirdInterfaceImpl()
{
    MyInterface*    pItf = new InterfaceImpl();

    pItf->Method1();
    pItf->Method2();
}

虽然这似乎可以满足您的需求(除了 C4250 警告您必须使用#pragma 进行抑制),但这不是我的方法。(我相信虚拟继承仍然不是所有编译器都支持的东西,但我可能是错的)。

我可能会选择包含,一旦样板代码是标识符,将其包装到某种宏映射中(类似于 ATL 或 MFC 中的映射),这将使它真的非常难以搞砸。

所以这将是我的宏观方法:

struct MyInterface
{
    virtual float Method1( int x ) = 0;
    virtual int Method2( float a, float b ) = 0;
    virtual void Method3( const TCHAR* sz ) = 0;
};

class Method1Impl
{
public:
    float Method1( int x ) {
        _tprintf( _T("Method1: %d\n"), x ); return 5.0;
    }
};

class Method2and3Impl
{
public:
    int Method2( float a, float b ) {
        _tprintf( _T("Method2: %f, %f\n"), a, b ); return 666;
    }

    void Method3( const TCHAR* sz ) {
        _tprintf( _T("Method3: %s"), sz );
    }
};


#define DECLARE_METHOD0( MethodName, Obj, R )   \
    virtual R MethodName() { return Obj.MethodName(); }

#define DECLARE_METHOD1( MethodName, Obj, R, A1 )   \
    virtual R MethodName( A1 a1 ) { return Obj.MethodName( a1 ); }

#define DECLARE_METHOD2( MethodName, Obj, R, A1, A2 )   \
    virtual R MethodName( A1 a1, A2 a2 ) { return Obj.MethodName( a1, a2 ); }


class InterfaceImpl : public MyInterface
{
public:
    DECLARE_METHOD1( Method1, m_method1Impl, float, int );
    DECLARE_METHOD2( Method2, m_method2and3Impl, int, float, float );
    DECLARE_METHOD1( Method3, m_method2and3Impl, void, const TCHAR* );

private:
    Method1Impl         m_method1Impl;
    Method2and3Impl     m_method2and3Impl;
};

void TestWeirdInterfaceImpl()
{
    MyInterface*    pItf = new InterfaceImpl();

    pItf->Method1( 86 );
    pItf->Method2( 42.0, 24.0 );
    pItf->Method3( _T("hi") );
}

直到 C++ 之神用可变参数宏为我们增光添彩,您必须为您拥有的每个参数数量声明一个。此外,如果您使用多重继承,则可能不需要第二个“Obj”参数,但正如我之前所说,如果有另一种解决方案,我会避免多重继承,在这种情况下是一个额外的参数。

然而,第三种选择可能是Pragmatic Programmer的作者似乎非常提倡的东西。如果您有大量不想重复的千篇一律的代码,因为正如您所指出的,它会引入人为错误。定义您自己的语言并编写代码生成器脚本(python、perl...)来自动创建实际代码。在这种情况下,您几乎可以指向一个界面,并让脚本为您写出文本。我自己没有尝试过做这种事情,但最近一直想在某个地方使用它,只是为了查看和评估结果。

于 2011-11-14T17:25:21.740 回答
0

这有点丑陋,可能会使可执行文件的大小膨胀,但是呢?

#include <iostream>

class Interface
{
public:
    virtual void method1() = 0;
    virtual void method2(int x) = 0;
};

template<typename T>
class MethodOneImpl : public T
{
 private:
    void method1(int x)
    { std::cout << "MethodOneImpl::method1() " << x << std::endl; }

 public:
    void method1() { method1(0); }
};

template<typename T>
class MethodTwoImpl : public T
{
 public:
    void method2(int x)
    { std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
};

class InterfaceImpl : public MethodTwoImpl<MethodOneImpl<Interface> >
{
};

int main()
{
    InterfaceImpl impl;
    impl.method1();
    impl.method2(0);
}
于 2011-11-14T16:45:37.057 回答
0
class AbsInterface
{
    // this is a simple interface class.
public:
    virtual void Method1() = 0;
    virtual void Method2() = 0;
};

class Functor1
{
public:
    void operator () ()
    {
        printf("This Is Void Functor1");
    }
};

class Functor2
{
public:
    void operator () ()
    {
    printf("This Is void Functor2");
    }
};

template <class T1, class T2>
class DerivedTemplateClass : public AbsInterface
{
public:
    virtual void Method1() { T1()(); }
    virtual void Method2() { T2()(); }
};

void main()
{
    DerivedTemplateClass<Stratege1, Stratege2> instance;
    instance.Method1();
    instance.Method2();
}

如您所见,我使用了 Functor。您可以使用模板和仿函数。

于 2011-11-15T08:45:59.133 回答
0

这是否符合您的目的?它维护接口关系并为您提供可维护的代码,而无需考虑客户端代码。

在 functionoid 中分离每个方法,并赋予您控制不同基类的每个方法的原型的能力。

#include <iostream>
#include <memory>
using namespace std;

    //No Control over this.
    class MethodOneImpl
    {
     private:
        void method1(int x)
        { std::cout << "MethodOneImpl::method1() " << x << std::endl; }

     public:
        void method1() { method1(0); }
    };

    class MethodTwoImpl
    {
     public:
        void myFunc(int x)
        { std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
    };

    //*************************//

    class Interface
    {
    public:
        virtual void method1() = 0;
        virtual void method2(int x) = 0;
    };

    //This is what i would do. //

    class BaseFuncType
    {
    //no pure virtual
    void Call()
          {
              throw "error";
          }
    void Call(int x)
          {
              throw "error";
          }
    };


    class Method1: public BaseFuncType
    {
    auto_ptr<MethodOneImpl> MethodPtr;
    public:
    Method1()
    {
        MethodPtr.reset(new MethodOneImpl());
    }
    virtual int Call() 
    {
        MethodPtr->method1(); 
    }
    };

    class Method2: public BaseFuncType
    {
        auto_ptr<MethodTwoImpl> MethodPtr;
    public:
    Method2()
    {
       MethodPtr.reset(new MethodTwoImpl());
    }
    virtual int Call(int x) 
    {
        MethodPtr->myFunc(x);
    }
    };
    template <class T1>
    class MethodFactory
    {
    private:
       T1 methodObj;
    public:
    void CallMethod()
    {
       methodObj.Call();
    }
    void CallMethod(int x)
    {
       methodObj.Call(x);
    }

    };
    class InterfaceImpl : public Interface
    {
        auto_ptr<MethodFactory> factory;
    public:
        virtual void method1() 
        {   
            factory.reset(new MethodFactory<Method1>());
            factory->CallMethod(); 
        }
        virtual void method2(int x) 
        { 
            factory.reset(new MethodFactory<Method2>());
            factory->CallMethod(x); 
        }
    };

    int main()
    {
        auto_ptr<Interface> inf;
        inf.reset(new InterfaceImpl);
        inf->method1();
        inf->method2(10);

        // This should be disallowed!
        // std::unique_ptr<MethodOneImpl> moi;
        // moi.reset(new InterfaceImpl);
    }
于 2011-11-15T20:25:08.117 回答
0

如果不让它们继承,似乎不可能将MethodOneImpl /MethodTwoImpl带入范围,因为如果不这样做,它们将不会填充虚拟表。C++ 遗漏了其他语言中的关键字之类的东西。InterfaceInterfaceimplements

因此,除非意识到/接受您正在寻找的只是一个桥接模式,它不满足要求 a)(您应该编写更多代码),中间 b)(代码​​不一定难以维护,否则您会被虚拟继承所困扰) 并且可以满足 c)。

这里(另一种)可能的解决方案(虽然只有减少膨胀的方法)

class Interface 
{ public:
 virtual void method1() {return impl_->method1();}
 private:
     Interface() {}
 protected:
     struct Impl {
         virtual void method1() = 0; };
     std::shared_ptr<Impl> impl_;
     Interface(const std::shared_ptr<Impl> &impl) : impl_(impl) {}
};

  class InterfaceImpl : public Interface
{
  struct Impl : public Interface::Impl {
      void method1()  { std::cout << "InterfaceImpl::method1() " << std::endl; }  } ;
public:
    InterfaceImpl() : Interface(std::shared_ptr<Impl> (new Impl)) {}
      };

  template <class T>
  class GenericInterfaceImpl :  public Interface {
      struct Impl : public Interface::Impl {
          Impl( T &t) : t_(t) {}
          void method1() { t_.method1() ; } 
          T t_; };
public:
    GenericInterfaceImpl() : Interface(std::shared_ptr<Impl> (new Impl(T()))) {}
      };

 struct AMethod1Impl {
     void method1() { std::cout << "AMethod1Impl::method1() " << std::endl; }  } ;

struct AnotherMethod1Impl_not_working {
     void method1_not_present() { std::cout << "AnotherMethod1Impl_not_working ::method1_not_present() " << std::endl; }  } ;

int main() {
 // compilation of next line would fail 
 // (lame attempt to simulate ompilation fail when pure function not implemented)
 // Interface inf;

 std::unique_ptr<Interface> inf;
 inf.reset(new InterfaceImpl);
 inf->method1();
 inf.reset(new GenericInterfaceImpl<AMethod1Impl>() );
 inf->method1();

 // compilation of next line would fail
 // inf.reset(new GenericInterfaceImpl<AnotherMethod1Impl_not_working>() );

    }
于 2011-11-17T09:56:14.883 回答