Creating an interface for an abstract class template in C++

前端 未结 5 563
暗喜
暗喜 2020-12-08 05:10

I have the code as below. I have a abstract template class Foo and two subclasses (Foo1 and Foo2) which derive from instantiations of the template. I wish to use pointers in

5条回答
  •  猫巷女王i
    2020-12-08 05:18

    Since functionB's argument type must be known in advance, you have only one choice: Make it a type which can hold every possible argument. This is sometimes called a "top type" and the boost libraries have the any type which gets quite close to what a top type would do. Here is what could work:

    #include 
    #include 
    using namespace boost;
    
    class IFoo {
        public:
        virtual void functionA()=0;
        virtual void functionB(any arg)=0; //<-can hold almost everything
    };
    
    template
    class Foo : public IFoo{
        public:
            void functionA(){  };
            void real_functionB(T arg)
            {
             std::cout << arg << std::endl;
            };
            // call the real functionB with the actual value in arg
            // if there is no T in arg, an exception is thrown!
    
            virtual void functionB(any arg)
            {
                real_functionB(any_cast(arg));
            }
    };
    
    int main()
    {
        Foo f_int;
        IFoo &if_int=f_int;
    
        if_int.functionB(10);
    
        Foo f_double;
        IFoo &if_double=f_double;
    if_int.functionB(10.0);
    
    }
    

    Unfortunately, any_cast does not know about the usual conversions. For example any_cast(any(123)) throws an exception, because it does not even try to convert the integer 123 to a double. If does not care about conversions, because it is impossible to replicate all of them anyway. So there are a couple of limitations, but it is possible to find workarounds if necessary.

提交回复
热议问题