0

I am building a static library that will be used on many future projects. I do not want to limit the interface of a particular function in this static library so the application codes can have flexibility in data types. This library will hold pure virtual base class pointers to objects the user will need.

At first, I tried templating this function. However, I would have to template the pure virtual base function as well (In the code shown, BBInterface::Go) - apparently this is not possible.

The visitor pattern sounded like it might be applicable, but I'm afraid I just don't get it. I furthermore don't understand if I can keep the static library black-boxed, or if the static library would have to be re-compiled and linked with a new set of "visitors" anytime someone adds a possible data type.

I am now trying to create a templated struct inside the function, which is then reinterpret_cast-ed to a (hopefully?) equivalent struct. See below

This seems to work for two inputs (A and B). This is ok, but I'd ideally want to use variadic templates to have potentially many inputs. This is over my head at this point. If anyone could help with that, it'd be great.

So, is there a more elegant way to keep an extensible function interface (BBContainer::Do in the code below)? Is there a way to avoid reinterpret_cast? Can I extend this to more than two templated arguments? Is there a way to check for success of reinterpret_cast like dynamic_cast?

#include <iostream>
#include <vector>
#include <map>
#include <memory>
using namespace std;

static const double values[] = {0., 1., 2., 3., 4., 5., 6. };

// ------ ASSUME THIS BLACK BOX AREA IS IN A STATIC LIBRARY THE USER CAN NOT MODIFY -------//
struct BBPacket {};

class BBInterface
{
public:
    virtual void Go(BBPacket&) = 0;
};

class BBContainer
{
public:
    void Add(const string aName, std::unique_ptr<BBInterface>&& aThing)
    {
        BBMap[aName] = std::move(aThing);
    }

    template <typename A, typename B>
    void Do(const std::string& aName, A& aVal, const B& aIndex)
    {
        struct NewPacket : public BBPacket
        {
            NewPacket(A& aVal, const B& aIndex) : mVal(aVal), mIndex(aIndex) {}
            A& mVal;
            const B& mIndex;
        };
        NewPacket temp(aVal, aIndex);
        this->Do(aName, temp);

    }

    void Do(const string& aName, BBPacket& aPacket)
    {
        BBMap[aName]->Go(aPacket);
    }

private:
    map<std::string, unique_ptr<BBInterface>> BBMap;
};


// ----- The user area is written by the user, and should not be included in the blackbox project! ---------
struct USingleValuePacket
{
    double& mVal;
    const int& mIndex;
};

struct UVectorValuePacket
{
    vector<double>& mVals;
    const vector<int>& mIndices;
};


class USingleExtractor : public BBInterface
{
    virtual void Go(BBPacket& aPacket)
    {
        USingleValuePacket& danger = reinterpret_cast<USingleValuePacket&>(aPacket);
        fprintf(stdout, "The current single value is %1.1f\n", danger.mVal);
        danger.mVal = values[danger.mIndex];
    }
};

class UVectorExtractor : public BBInterface
{
    virtual void Go(BBPacket& aPacket)
    {
        UVectorValuePacket& danger = reinterpret_cast<UVectorValuePacket&>(aPacket);
        for (int i = 0; i < danger.mVals.size(); ++i)
        {
            fprintf(stdout, "The current vector value %i is %1.1f\n",i, danger.mVals[i]);
            danger.mVals[i] = values[danger.mIndices[i]];
        }
    }
};


int main()
{
    BBContainer a;
    a.Add("f", std::unique_ptr<USingleExtractor>(new USingleExtractor));
    a.Add("g", std::unique_ptr<UVectorExtractor>(new UVectorExtractor));
    double val = 0.;
    int index = 4;
    a.Do("f", val, index);
    fprintf(stdout, "Expected value is 4.0 and I get %1.1f\n", val);

    std::vector<double> valVec(3);
    std::vector<int> indexVec; indexVec.push_back(0);  indexVec.push_back(2); indexVec.push_back(5);
    a.Do("g", valVec, indexVec);
    fprintf(stdout, "Expected value for index 0 is 0.0 and I get %1.1f\n", valVec[0]);
    fprintf(stdout, "Expected value for index 1 is 2.0 and I get %1.1f\n", valVec[1]);
    fprintf(stdout, "Expected value for index 2 is 5.0 and I get %1.1f\n", valVec[2]);

//  a.Do("g", val, index); // This will go into UVectorExtractor with USingleValuePacket data - Not compatible!

    return 0;
}

EDIT:

I want BBContainer::Do to have a flexible signature (in this example I use (string, double&, const int&) and (string, vector&, const vector&), but I may have many more). At the same time I do not want to modify BBInterface (for example with Go(double&, const int), Go(vector&, const vector&), and so on). I can assume the derived class of BBInterface knows what data its particular implementation of Go requires. So how do I forward generic data from BBContainer::Do to the derived classes of BBInterface when it only has access to the BBInterface base class - which is not allowed to be specialized? And, is there a more type-safe method than generating a templated struct in the BBInterface base class and using reinterpret_cast in its derived classes?

7
  • What are your actual requirements? I'm having a bit of difficulty inferring from your particular attempt at implementation exactly what functionality you wish to provide. I think your question needs to be answered at a higher design level -- e.g. identify just what needs to be runtime polymorphism, what needs to be compile-time polymorphism, and what syntactic sugar to offer -- rather than of the form "replace this piece of an implementation with something else".
    – user1084944
    Mar 14, 2015 at 8:24
  • @Hurkyl I will try to explain it better in an edit.
    – DSM
    Mar 14, 2015 at 9:06
  • reinterpret_cast is wrong in almost every case people want to use it anyway. Mar 14, 2015 at 9:38
  • The main reason you seem to want BBContainer::Do to have a flexible signature is so that it can construct a packet -- why not just accept a packet as input? And you can make packets how how to send themselves to a BBInterface& if its the right type. (and you could metaprogram some syntactic sugar on top of that if you really wanted to)
    – user1084944
    Mar 14, 2015 at 9:45
  • I should point out that your edit doesn't talk about requirements: you still seem to be thinking about the question in terms of how to implement something in a particular way, rather than what functionality you wish to provide.
    – user1084944
    Mar 14, 2015 at 9:47

1 Answer 1

0

As Hurkyl pointed out, I should just make a packet. It seems good enough with that and a helper function to keep the interface of Do clean and a dynamic_cast instead of reinterpret_cast. I'm still working on variadic templates for variable length packets.

New packet:

template<typename A, typename B>
struct UPacket : public BBPacket
{
    UPacket(A& aVal, const B& aIndex) : mVal(aVal), mIndex(aIndex) {}
    A& mVal;
    const B& mIndex;
};

Helper function:

template <typename A, typename B>
void Do(BBContainer& a, const string& aName, A& aVal, const B& aIndex)
{
    a.Do(aName, UPacket<A, B>(aVal, aIndex));
}

Usage:

...
double val = 0.;
int index = 4;
Do(a,"f", val, index);
...
std::vector<double> valVec(3);
std::vector<int> indexVec; indexVec.push_back(0);  indexVec.push_back(2); indexVec.push_back(5);
Do(a, "g", valVec, indexVec); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.