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 8624193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T07:27:50+00:00 2026-06-12T07:27:50+00:00

I’d like advice on a way to cache a computation that is shared by

  • 0

I’d like advice on a way to cache a computation that is shared by two derived classes. As an illustration, I have two types of normalized vectors L1 and L2, which each define their own normalization constant (note: against good practice I’m inheriting from std::vector here as a quick illustration– believe it or not, my real problem is not about L1 and L2 vectors!):

#include <vector>
#include <iostream>
#include <iterator>
#include <math.h>

struct NormalizedVector : public std::vector<double> {
  NormalizedVector(std::initializer_list<double> init_list):
    std::vector<double>(init_list) { }
  double get_value(int i) const {
    return (*this)[i] / get_normalization_constant();
  }
  virtual double get_normalization_constant() const = 0;
};

struct L1Vector : public NormalizedVector {
  L1Vector(std::initializer_list<double> init_list):
    NormalizedVector(init_list) { }
  double get_normalization_constant() const {
    double tot = 0.0;
    for (int k=0; k<size(); ++k)
      tot += (*this)[k];
    return tot;
  }
};

struct L2Vector : public NormalizedVector {
  L2Vector(std::initializer_list<double> init_list):
    NormalizedVector(init_list) { }
  double get_normalization_constant() const {
    double tot = 0.0;
    for (int k=0; k<size(); ++k) {
      double val = (*this)[k];
      tot += val * val;
    }
    return sqrt(tot);
  }
};

int main() {
  L1Vector vec{0.25, 0.5, 1.0};
  std::cout << "L1 ";
  for (int k=0; k<vec.size(); ++k)
    std::cout << vec.get_value(k) << " ";
  std::cout << std::endl;

  std::cout << "L2 ";
  L2Vector vec2{0.25, 0.5, 1.0};
  for (int k=0; k<vec2.size(); ++k)
    std::cout << vec2.get_value(k) << " ";
  std::cout << std::endl;
  return 0;
}

This code is unnecessarily slow for large vectors because it calls get_normalization_constant() repeatedly, even though it doesn’t change after construction (assuming modifiers like push_back have appropriately been disabled).

If I was only considering one form of normalization, I would simply use a double value to cache this result on construction:

struct NormalizedVector : public std::vector<double> {
  NormalizedVector(std::initializer_list<double> init_list):
    std::vector<double>(init_list) {
    normalization_constant = get_normalization_constant();
  }
  double get_value(int i) const {
    return (*this)[i] / normalization_constant;
  }

  virtual double get_normalization_constant() const = 0;
  double normalization_constant;
};

However, this understandably doesn’t compile because the NormalizedVector constructor tries to call a pure virtual function (the derived virtual table is not available during base initialization).

Option 1:
Derived classes must manually call the normalization_constant = get_normalization_constant(); function in their constructors.

Option 2:
Objects define a virtual function for initializing the constant:

init_normalization_constant() {
  normalization_constant = get_normalization_constant();
}

Objects are then constructed by a factory:

struct NormalizedVector : public std::vector<double> {
  NormalizedVector(std::initializer_list<double> init_list):
    std::vector<double>(init_list) {
    //    init_normalization_constant();
  }
  double get_value(int i) const {
    return (*this)[i] / normalization_constant;
  }

  virtual double get_normalization_constant() const = 0;
  virtual void init_normalization_constant() {
    normalization_constant = get_normalization_constant();
  }

  double normalization_constant;
};

// ...
// same code for derived types here
// ...

template <typename TYPE>
struct Factory {
  template <typename ...ARGTYPES>
  static TYPE construct_and_init(ARGTYPES...args) {
    TYPE result(args...);
    result.init_normalization_constant();
    return result;
  }
};

int main() {
  L1Vector vec = Factory<L1Vector>::construct_and_init<std::initializer_list<double> >({0.25, 0.5, 1.0});
  std::cout << "L1 ";
  for (int k=0; k<vec.size(); ++k)
    std::cout << vec.get_value(k) << " ";
  std::cout << std::endl;

  return 0;
}

Option 3:
Use an actual cache: get_normalization_constant is defined as a new type, CacheFunctor; the first time CacheFunctor is called, it saves the return value.

In Python, this works as originally coded, because the virtual table is always present, even in __init__ of a base class. In C++ this is much trickier.

I’d really appreciate the help; this comes up a lot for me. I feel like I’m getting the hang of good object oriented design in C++, but not always when it comes to making very efficient code (especially in the case of this sort of simple caching).

  • 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-12T07:27:51+00:00Added an answer on June 12, 2026 at 7:27 am

    I suggest the non-virtual interface pattern. This pattern excels when you want a method to provide both common and unique functionality. (In this case, caching in common, computation in uniqueness.)

    http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

    // UNTESTED
    struct NormalizedVector : public std::vector<double> {
     ...
      double normalization_constant;
      bool cached;
      virtual double do_get_normalization_constant() = 0;
      double get_normalization_constant() {
        if(!cached) {
          cached = true;
          normalization_constant = do_get_normalization_constant();
        }
        return normalization_constant;
    };
    

    P.s. You really ought not publicly derive from std::vector.

    P.P.s. Invalidating the cache is as simple as setting cached to false.


    Complete Solution

    #include <vector>
    #include <iostream>
    #include <iterator>
    #include <cmath>
    #include <algorithm>
    
    struct NormalizedVector : private std::vector<double> {
    private:
      typedef std::vector<double> Base;
    protected:
      using Base::operator[];
      using Base::begin;
      using Base::end;
    public:
      using Base::size;
    
      NormalizedVector(std::initializer_list<double> init_list):
        std::vector<double>(init_list) { }
      double get_value(int i) const {
        return (*this)[i] / get_normalization_constant();
      }
    
      virtual double do_get_normalization_constant() const = 0;
      mutable bool normalization_constant_valid;
      mutable double normalization_constant;
      double get_normalization_constant() const {
        if(!normalization_constant_valid) {
          normalization_constant = do_get_normalization_constant();
          normalization_constant_valid = true;
        }
        return normalization_constant;
      }
    
      void push_back(const double& value) {
        normalization_constant_valid = false;
        Base::push_back(value);
      }
    
      virtual ~NormalizedVector() {}
    };
    
    struct L1Vector : public NormalizedVector {
      L1Vector(std::initializer_list<double> init_list):
        NormalizedVector(init_list) { get_normalization_constant(); }
      double do_get_normalization_constant() const {
        return std::accumulate(begin(), end(), 0.0);
      }
    };
    
    struct L2Vector : public NormalizedVector {
      L2Vector(std::initializer_list<double> init_list):
        NormalizedVector(init_list) { get_normalization_constant(); }
      double do_get_normalization_constant() const {
        return std::sqrt(
          std::accumulate(begin(), end(), 0.0,
            [](double a, double b) { return a + b * b; } ) );
      }
    };
    
    std::ostream&
    operator<<(std::ostream& os, NormalizedVector& vec) {
      for (int k=0; k<vec.size(); ++k)
        os << vec.get_value(k) << " ";
      return os;
    }
    
    int main() {
      L1Vector vec{0.25, 0.5, 1.0};
      std::cout << "L1 " << vec << "\n";
    
      vec.push_back(2.0);
      std::cout << "L1 " << vec << "\n";
    
      L2Vector vec2{0.25, 0.5, 1.0};
      std::cout << "L2 " << vec2 << "\n";
    
      vec2.push_back(2.0);
      std::cout << "L2 " << vec2 << "\n";
      return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have two tables with like below codes: Table: Accounts id | username |
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

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.