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

  • SEARCH
  • Home
  • 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 8300649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T16:38:21+00:00 2026-06-08T16:38:21+00:00

The X: What I want to do: I have the types: BaseType and DerivedType<int

  • 0

The X: What I want to do:

I have the types: BaseType and DerivedType<int k> (see code below), and I need to handle a collection of K vectors of the derived types std::vector<DerivedType<k>>, k = 1...K. I’d like to access the objects in these vectors, and perform an operation on them that depends on k. K is a compile time constant. The problem is illustrated in the implementation:

The types are defined as:

#include <iostream>
#include <algorithm>

struct BaseType { // Interface of the DerivedTypes
  virtual void print(){std::cout << "BaseType!" << std::endl; }
};

template< int k >
struct DerivedType : public BaseType {
  static const int k_ = k;
  // ... function calls templated on k ...
  void print(){std::cout << "DerivedType: " << k_ << std::endl;}
};

template< int k >
void doSomething ( DerivedType<k>& object ) { object.print(); }

And what I want to do is:

int main() {

  // My collection of vectors of the derived types:
  std::vector<DerivedType<0>> derType0(2);
  std::vector<DerivedType<1>> derType1(1);
  std::vector<DerivedType<2>> derType2(3);
  // ... should go to K: std::vector<DerivedType<K>> derTypeK;

  // Iterate over the derived objects applying a k-dependent templated function:
  std::for_each(begin(derType0),end(derType0),[](DerivedType<0>& object){
    doSomething<0>(object);
  });
  std::for_each(begin(derType1),end(derType1),[](DerivedType<1>& object){
    doSomething<1>(object);
  });
  std::for_each(begin(derType2),end(derType2),[](DerivedType<2>& object){
    doSomething<2>(object);
  });

  return 0;
}

I want to avoid repeating code, such that I only have to change K, which is a compile time constant of O(10). Ideally, I would have something “more like” this:

// Pseudocode: do not try to compile this

create_derived_objects(DerivedType,K)
  = std::vector< std::vector<DerivedType<k>>* > my_K_derived_types;                                                  

for each vector<DerivedType<k>>* derivedTypes in my my_K_derived_types
  for each object in (*derivedTypes)
    doSomething<k> on object of type derivedType<k>
    // I could also restrict doSomething<k> to the base interface

Each vector of derived types contains O(10^6) to O(10^9) objects. The inner-most loops are the most time consuming part of my application making dynamic_cast only an option for the outer-most loop.

The Y: what I have tryed without succes.

I am at the moment studying the Abrahams C++ Template Metaprogramming book to see if I could use boost::mpl. I am also doing the tutorials on boost::fusion to see if I could use it too. However, the learning curve of these libraries is rather large, so I wanted to ask first before I invest a week in something when a better and simpler solution is available.

My first try was to wrapp my vectors std::vector<DerivedType<k>> such that I can create a vector<WrappedDerivedTypes*>, and access each of the single vectors separately within a for_each loop. However, in the loop I have a series of if(dynamic_cast<std::vector<DerivedType<0>>>(WrappedVector) != 0 ){ do for_each loop for the derived objects } else if( dynamic_cast...) { do...} ... that I wasn’t able to eliminate.

  • 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-06-08T16:38:22+00:00Added an answer on June 8, 2026 at 4:38 pm

    What about a recursive solution based on a generic linked list of vectors, a strategy pattern and a thing that applies strategies recursively through the linked list? (note: see the improved version at the end):

    #include <iostream>
    #include <vector>
    
    template <int j>
    class holder {
    public:
        const static int k = j;
    };
    
    template <int j>
    class strategy {
    public:
        void operator()(holder<j> t)
        {
            std::cout << "Strategy " << t.k << std::endl;
        }
    };
    
    template <int k>
    class lin_vector {
    private:
        std::vector<holder<k>> vec;
        lin_vector<k-1> pred;
    public:
        lin_vector(const lin_vector<k-1> &pred, std::vector<holder<k>> vec)
            : vec(vec), pred(pred) { }
        std::vector<holder<k>> get_vec() { return vec; }
        lin_vector<k-1> &get_pred() { return pred; }
    };
    
    template <>
    class lin_vector<0> {
    public:
        lin_vector() { }
    };
    
    template <int k, template <int> class strategy>
    class apply_strategy {
    public:
        void operator()(lin_vector<k> lin);
    };
    
    template <int k, template <int> class strategy>
    void apply_strategy<k, strategy>::operator()(lin_vector<k> lin)
    {
        apply_strategy<k-1, strategy>()(lin.get_pred());
        for (auto i : lin.get_vec())
        strategy<k>()(i);
    }
    
    template <template <int> class strategy>
    class apply_strategy<0, strategy>
    {
    public:
        void operator()(lin_vector<0> lin) { /* does nothing */ } 
    };
    
    
    template <int k>
    lin_vector<k> build_lin()
    {
        return lin_vector<k>(build_lin<k-1>(), {holder<k>()});
    }
    
    template <>
    lin_vector<0> build_lin()
    {
        return lin_vector<0>();
    }
    
    int main(void)
    {
        apply_strategy<5, strategy>()(build_lin<5>());
    }
    

    Compile it with a C++11 compiler.
    Most probably you’ll find unsatisfactory the fact that building a lin_vector requires a lot of copying, but you can specialize the structure to suit your needs (perhaps substituting the pred with a pointer or embedding the creation strategy straight into the linked list).

    EDIT: here there is an improved version which avoids a lot of copying and handles list building and processing in a more coherent and uniform way:

    #include <iostream>
    #include <vector>
    
    template <int j>
    class holder {
    public:
        const static int k = j;
    };
    
    template <int k>
    class lin_vector {
    private:
        std::vector<holder<k>> vec;
        lin_vector<k-1> pred;
    public:
        std::vector<holder<k>> &get_vec() { return vec; }
        lin_vector<k-1> &get_pred() { return pred; }
    };
    
    template <>
    class lin_vector<0> {
    public:
        lin_vector() { }
    };
    
    template <int k, template <int> class strategy>
    class apply_strategy {
    public:
        void operator()(lin_vector<k> &lin);
    };
    
    template <int k, template <int> class strategy>
    void apply_strategy<k, strategy>::operator()(lin_vector<k> &lin)
    {
        apply_strategy<k-1, strategy>()(lin.get_pred());
        strategy<k>()(lin.get_vec());
    }
    
    template <template <int> class strategy>
    class apply_strategy<0, strategy>
    {
    public:
        void operator()(lin_vector<0> &lin) { /* does nothing */ } 
    };
    
    template <int j>
    class strategy {
    public:
        void operator()(std::vector<holder<j>> &t)
        {
            std::cout << "Strategy " << j << ", elements: ";
            for (auto v : t)
                std::cout << v.k << " ";
            std::cout << std::endl;
        }
    };
    
    template <int j>
    class build_strategy {
    public:
        void operator()(std::vector<holder<j>> &t)
        {
            for (unsigned int i = 0; i < j; i++)
                t.push_back(holder<j>());
        }
    };
    
    int main(void)
    {
        const int K = 5;
        lin_vector<K> list;
        apply_strategy<K, build_strategy>()(list);
        apply_strategy<K, strategy>()(list);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an input box which I want to handle two types of information,
I want to have a generic function for a few types such as long,
I have some types which are generated by a web service reference. I want
I have 2 custom post types - offered and wanted. I want these items
I have a question concerning subtypes of built-in types and their constructors. I want
Lets say that we have the following code Base() { ... } Derived :
I want to find out which methods have been assigned to handle events of
I have the following XML: <types> <type> <name>derived</name> <superType>base</superType> <properties> <property> <name>B1</name> </property> <property>
I need to pass a List of Types to a method, but I want
I have the following code, which I want to use to modify the ProfileBase

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.