Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7367907
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T03:35:49+00:00 2026-05-29T03:35:49+00:00

Interface: template <class T> class Interface{ public: typedef T Units; virtual T get() =

  • 0

Interface:

template <class T>
class Interface{
    public:
    typedef T Units;
    virtual T get() = 0;
};

Implementation1:

class Implementation1: public Interface<float> {
    public:

    float get() {
       return 0.0f;
    }

};

Implementation2:

class Implementation2: public Interface<int> {
    public:

    int get() {
       return 0;
    }

};

Container (with errors):

class Container{
    private:
    Interface* floatGetter;
    int n;
    Timer::Units* array;

    public:
    Container(Interface* floatGetter, int n) {
        this->floatGetter= floatGetter;
        this->n = n;
        array = new Timer::Units[n];
    }

    ~Container() {

    }

};

For more details, I have a template interface and a derived class from this interface without template. Some other class take an object of the derived class but it takes the object as an interface (in other words, dependency injection). But the type of the interface in this class is defined by the interface implementation. How to implement this idea in C++?

Edit1:

Example:

Interface<float> myInterface1 = new Implementation1();
Interface<int> myInterface2 = new Implementation2();
Container container1 = new Container(myInterface1, 10);
Container container2 = new Container(myInterface2, 10);

I need that container understands interface template argument from its implementation.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T03:35:50+00:00Added an answer on May 29, 2026 at 3:35 am

    OK, first, an explanation of the problem here. What’s required is an interface, that defines a virtual method, used to get a value with a templated type. Since what we want is an interface, the get method has to be virtual. On the other hand, we would like to be able to return different types, so we want to templetize it. However, a virtual method can not be templetized, because the compiler wouldn’t know which instantions of that method to include in the vtable.

    One solution is to do what’s done in the question, i.e. templetize the interface class. An important property of template types is that different instantiations of the same class are completely different types. They don’t share a common base, and they’re not convertible to each other. We simply can not have an Interface<Generic> pointer going around in regular functions, with their get() methods being called. Consider this: Every instantion of the Interface template type has a different signature for the get() method. This means that while that method is being called, different things have to happen on the stack. How could the compiler know which version of the get() method to call (how to prepare the stack for the function call) if all it has is a Interface<Generic> pointer.

    I can think of two general solutions to that problem.

    1. Remove all template mumbo-jumbo and make the get() method return a type-erased object, such as boost::variant or boost::any. Correct me if I’m wrong here(*), but boost::variant is like a union that remembers which type of the union is assigned, while boost::any is like a void *, but it remembers what type it’s pointing to. This solution path implies two things:
      a) The types of the returned objects will be resolved at runtime, and there will be some overhead while manipulating these types.
      b) The child classes of Interface will have to manage one of these type-erased objects, making them more complicated.

    2. Take the template mumbo-jumbo to the extreme and refer to Interface objects always in a templetized context, so that the compiler generates the right function calls during the instantiations of those contexts. I gave an example below which follows this path. The example creates a container for holding together different types of Interface<> objects, while enabling the application of templetized functionals (is it correct to call this generally “visitors”?) to them. Note that in that example, the Interface objects with different type parameters are actually kept in different std::lists in that container class, so in the runtime, there’s no need to resolve their types.

    Disclaimer: What follows is an overkill…

    Here’s how you can have a container of the “interface” template class with different template arguments. I’ve used an std::list to keep the instances, but you can change it.

    #include<boost/fusion/container/vector.hpp>
    #include<boost/fusion/algorithm.hpp>
    #include<boost/mpl/transform.hpp>
    #include<boost/mpl/contains.hpp>
    #include<boost/utility/enable_if.hpp>
    #include<boost/type_traits/add_reference.hpp>
    #include<list>
    #include<algorithm>
    #include <iostream>
    
    using namespace boost;
    
    template <class T>
    class Interface{
        public:
        typedef T Units;
        virtual T get() = 0;
    };
    
    class Implementation1: public Interface<float> {
        public:
    
        float get() {
           return 0.0f;
        }
    
    };
    
    class Implementation2: public Interface<int> {
        public:
    
        int get() {
           return 5;
        }
    
    };
    
    template<class element>
    struct to_list {
        typedef std::list<Interface<element> *> type;
    };
    
    template<class elementVector>
    struct to_containers {
        typedef typename mpl::transform<elementVector,to_list<mpl::_1> >::type type;
    };
    
    class Container{
        typedef fusion::vector<int,float> AllowedTypes;
        typename to_containers<AllowedTypes>::type containers;
    
    public:
        template<class type> typename enable_if<mpl::contains<AllowedTypes,type>,void>::type 
        /*void*/ add(Interface< type/*included in AllowedTypes*/ > & floatGetter) {
            fusion::deref(fusion::find<typename to_list<type>::type >(containers))
                /*<type> container*/.push_back(&floatGetter);
        }
    
        template<class functional>
        void apply(functional f) {
            fusion::for_each(containers,applyFunctional<functional>(f));
        }
    
    private:
        template<class functional>
        struct applyFunctional {
            functional f;
            applyFunctional(functional f): f(f){}
            template<class T> void operator()(T & in) const {
                std::for_each(in.begin(), in.end(),f);
            }
        };
    
    };
    
    struct printValueFunctional {
        template<class element>
        void operator()(Interface<element> * in) const {
            std::cout<<"Hi, my value is:"<<in->get()<<"\n";
        }
    };
    
    int main() {
    
        Implementation1 impl1;
        Implementation2 impl2;
        Interface<float> &myInterface1 = impl1;
        Interface<int> &myInterface2 = impl2;
        Container container;
        container.add(myInterface1);
        container.add(myInterface2);
        container.apply(printValueFunctional());
        return 0;
    }
    

    And the output is:

    Hi, my value is:5
    Hi, my value is:0
    

    Well, this really is a huge overkill for most applications, but you asked for it 🙂

    If you just want an interface, that can return different things, you could also consider boost.variant. The example above is truly valuable for all the static polymorphism it uses.

    EDIT: David has pointed something important, it might be a pitfall, if you, for some reason, assume otherwise. This container doesn’t really stay true to the order of the item insertions. The order of your functional calls might not happen in the order of the insertions of the items, i.e., assume that the iteration will be in a “random” order.

    (*) boost::variant and boost::any are discussed here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Timer.h: template<class T> class Timer { public: typedef T Units; virtual Units get() =
interface I { int J(); } class A : I { public int J(){return
Suppose a construct like this: class Interface { public: template <typename T> virtual void
Consider the following setup: I am given an interface template<class T> void FooClass<T>::foo(boost::function<double (int)>
I'm using a library that defines an interface: template<class desttype> void connect(desttype* pclass, void
interface A { void hi(); } class AImpl implements A { public void hi()
I have the following piece of code: class ICookable { public: virtual void CookMe
From wikipedia: // A class template to express an equality comparison interface. template<typename T>
I have a class similar to the following: class SomeClass { public: template<typename... Args>
Suppose I have this class hierarchy: class A { public: virtual void foo(Base *b)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.