Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ / C# ABC design pattern with static member
    primarykey
    data
    text
    <p>I have an ABC class I want to make generic:</p> <pre><code>struct BinaryVariable { static const int N = 2; static std::string outcome_names[N] = { "heads", "tails" }; }; struct EvidenceBinaryVariable : public BinaryVariable { double likelihoods[ BinaryVariable::N ]; }; struct LatentBinaryVariable : public BinaryVariable { }; </code></pre> <p>The important thing is that every instance of these three nodes shares the same <code>::N</code>, and uses the same memory for the <code>outcome_names</code> variable. <br> <br></p> <p>Let's say I want to make these three node types to also allow for a variable with 6 possible outcomes (i.e. I want to support dice in addition to coins). In C++ I can do this with templates:</p> <pre><code>#include&lt;cstddef&gt; #include&lt;string&gt; template&lt;std::size_t N&gt; struct DiscreteVariable { static std::string outcome_names[N]; }; template&lt;std::size_t N&gt; struct EvidenceVariable : public DiscreteVariable&lt;N&gt; { double likelihoods[ DiscreteVariable::N ]; }; template&lt;std::size_t N&gt; struct LatentVariable : public DiscreteVariable&lt;N&gt; { }; int main() { LatentVariable&lt;2&gt; schrodingers_coin; LatentVariable&lt;6&gt; schrodingers_die; } </code></pre> <p>I can't figure out a way to get the three types to have a static <code>outcome_names</code> member (and where <code>shrodingers_coin.outcome_names</code> and <code>schrodingers_dice.outcome_names</code> do not refer to the same static piece of memory) without using templates in this way.</p> <p>C# only supports type-based templates (i.e. you could provide <code>&lt;int&gt;</code> but not <code>&lt;6&gt;</code>.</p> <p>First question: is there a good design pattern for this in C++? (e.g. should I use these triplets as internal classes within a master class?)</p> <p>Second question: does this good design pattern work in C# (or is C++'s template magic just a good fit here)?</p> <p>Just for posterity, the reason I want these static is because I have tons of these objects, and am writing something where efficiency is paramount (think big data). </p> <p>Thanks a lot for your help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload