How do I declare an array of red black trees? - d

When I want to initialize a red black tree I do as in the documentation.
auto rbt = redBlackTree(1,2,3,4)
but if I want to declare it globally or make an array of red black trees I don't know how to do it and the documentation is not helping. I've tried various things and I frequently get errors similar to: redBlackTree!int is used as a type Can you help me? I could do it if I knew what to put instead of auto, ie, if I knew the type of redBlackTree.
I want to declare a red black tree in global scope or declare an array for which I need to declare the type, I want to do something like this:
type rbt;
void main() {
rbt.insert(3);
}
or this:
void main{
type[2] rbt;
rbt[0].insert(1);
}

You don't need to know the type of redBlackTree. You can query for at compile-time with typeof:
alias RBTree = typeof(redBlackTree(1));
RBTree rbt = redBlackTree(1, 2, 3);
This is a common and an encouraged pattern as many functions in D return Voldemort types (types that cannot be named).
In your example the type is RedBlackTree!int. If you don't use an IDE, an easy way to discover the type is pragma(msg, typeof(<functionCall>(<args>)));.
Furthermore, I should note that declaring an array of RedBlackTree works with auto:
auto arr = [redBlackTree(1, 2), redBlackTree(3, 4)];
For more help, please feel free to post the exact code that failed.

The type (using long instead of int) is RedBlackTree!long, here are some examples. Remember you have to use new to initialize the class.
import std.stdio;
import std.container;
RedBlackTree!long rbtree;
RedBlackTree!long[2] rbarray;
RedBlackTree!long[] rbdynamicarr;
RedBlackTree!long[][] rbmat;
void main() {
rbtree.writeln;
rbtree = new RedBlackTree!long;
rbtree.insert(3);
rbtree.writeln;
rbarray.writeln;
rbarray = new RedBlackTree!long[2];
rbarray.writeln;
rbdynamicarr.writeln;
int n = 3;
rbdynamicarr = new RedBlackTree!long[n];
rbdynamicarr.writeln;
rbmat.writeln;
int m = 2;
rbmat = new RedBlackTree!long[][](n,m);
rbmat.writeln;
alias RBTree = typeof(redBlackTree!long(1L));
RBTree rbalias;
rbalias = new RBTree;
rbalias.writeln;
RBTree[3] crayola;
crayola.writeln;
typeid(redBlackTree(1)).writeln;
RedBlackTree!(long, "a < b", false) hola;
hola = new RedBlackTree!(long, "a < b", false);
hola.writeln;
}

Related

Using template meta programming (TMP) to make homogeneously storable templated configurants

Sorry for the atrocious title.
The scenario is that I have a configuration system in my program, that needs to able to hold values of all types. These values (configurants) need to be held in a homogenous container.
For example: (this is pseudo-code, I'm not sure how this would actually look)
configurant i(64);
configurant b(true);
configurant f(128.f);
configurant custom(Color(255, 255, 255));
vector<configurant> confs;
confs.emplace_back(i);
confs.emplace_back(b);
confs.emplace_back(f);
confs.emplace_back(custom);
// some form of accessing the vector with proper configurant type here:
// casting?
Like I said, I don't know how this system would look in practice. I know that a statement like
auto color = confs.at(3).rgb();
is generally not possible in C++, but is there something I could do with templated metaprogramming to try and get as close as possible to this solution?
(perhaps the configurants could be mapped with their type? but this would not be a compile time operation)
I'm looking to create a system that is storable homogeneously, immediately accessible (not stored on the heap) and that evaluates the validity of operations at compile time.
Open to any suggestions.
And before the comments come in, I've experimented with std::any/std::any_cast, std::variant, the visitor pattern, and other things of that nature. I'm not looking to use any of those systems.
EDIT To avoid confusion, there are N configurants: it is not a statically sized group of configurants. More configurants would be added by the user of this interface.
EDIT 2 Additional example of desired usage
class foo {
configurant enabled;
configurant bar;
public:
foo() {
this->enabled = configurant(true);
this->bar = configurant(5);
}
void body() {
if(this->enabled) {
std::cout << (this->bar < 100) << "\n";
}
}
// It also needs to be kept in mind that these configurant classes
// cannot be templated (directly, at least), since they need to be stored in
// a homogeneous container.
};
Because of this requirement
"that evaluates the validity of operations at compile time.",
this means that your example
auto color = confs.at(3).rgb();
will only work with the index 3 known at compile time
(why not 2 or 4?).
This index is not very relevant/useful in this situation.
May be should you simply consider a structure providing
the required data with a proper name instead of a
compile-time index?
struct Confs
{
configurant<int> i;
configurant<bool> b;
configurant<float> f;
configurant<Color> custom;
};
...
Confs confs{64, true, 128.f, Color(255, 255, 255)};
auto color = confs.custom.rgb();
Something like this could rely on a compile-time index
but I don't really see the benefit over a named member.
auto confs=std::make_tuple(64, true, 128.0f, Color{255, 255, 255});
auto color = std::get<3>(confs).rgb();

Using Google Mock for pointer to array allocated in call?

Given the following C/C++ code:
#define MAX_LEN 256
typedef struct {
int id;
char val[MAX_LEN];
} CfgInfoType;
CfgInfoType* pCfgInfo;
int getCfg(CfgInfoType** ppCfgInfo)
{
int n = determineN(); /* An example, real code a little more complex */
*ppCfgInfo = (CfgInfoType*) malloc(sizeof(CfgInfoType) * n);
/* Code to fill in *pCfgInfo array here */
return n;
}
I do not like this code, it allocates memory as a side effect that requires the caller to free. However before I change the code I'd like to mock getCfg() so that I can build a set of characterization tests around the callers. getCfg() is basically allocating and returning a pointer to a contiguous array. But I have not been able to setup a Google Mock that will populate that array for getCfg() callers/clients. In addition, the callers free the memory, so to test the callers, the mock actually has to allocate the memory or mock the memory as allocated so the free() calls do not cause a segmentation violation. Tried many things, among them:
CfgInfoType* pCfgInfo = (CfgInfoType*) malloc(sizeof(CfgInfoType) * 2);
pCfgInfo[0].id = 1;
strcpy(pCfgInfo[0].val, "value 1");
pCfgInfo[1].id = 2;
strcpy(pCfgInfo[1].val, "value 2");
EXPECT_CALL(mockObj, getCfg(NotNull())).WillOnce(DoAll(SetArrayArgument<0>(pCfgInfo, pCfgInfo+2), Return(2));
or:
EXPECT_CALL(mockObj, getCfg(NotNull())).WillOnce(DoAll(SetArgPointee<0>(pCfgInfo), Return(2));
Beginning to think this is not doable. Or should I say not "mockable"?
Thanks in advance for any help!
Chris
This is certainly doable. What you need is a custom action:
ACTION_P(SetCfgInfoPtrToPtr, value)
{
*reinterpret_cast<CfgInfoType**>(arg0) = value;
}
The action above does what you want but it is too restrictive because the type of pointer and argument index are fixed. I suggest usage of a generalized templatized action that allows you to set the type and argument index via template. This can be achieved via ACTION_TEMPLATE. The first template parameter (Type) is the type of pointer, the second (uIndex) is an integral value that represents index of the function parameter. Inside ACTION_TEMPLATE, you can access all arguments via args, which is a std::tuple. Therefore, we can apply std::get in combination with uIndex to get the correct function parameter (For example, std::get<0>(args) gives us arg0). We then cast this parameter to Type**, dereference it and assing the desired value to the pointee. Here is a complete definition:
ACTION_TEMPLATE(SetArgPtrToPtr, HAS_2_TEMPLATE_PARAMS(typename, Type, unsigned, uIndex), AND_1_VALUE_PARAMS(value))
{
*reinterpret_cast<Type**>(std::get<uIndex>(args)) = value;
}
This action , as well as the value that will be assigned to the pointee.
In your case, this is how you should use it:
EXPECT_CALL(mockObj, getCfg(NotNull()))
.WillOnce(
DoAll(
SetArgPtrToPtr<CfgInfoType, 0>(pCfgInfo),
Return(2)
)
);
There is nice API called Typemock Isolator++ for unit-test frameworks. It has a simple solution for mocking methods with reference parameters. Take a look:
TEST_METHOD(RETAndSpecificReturnValue)
{
//Arrange
int n = 2;
CfgInfoType* pCfgInfo = (CfgInfoType*)malloc(sizeof(CfgInfoType) * n);
pCfgInfo[0].id = 1;
strcpy(pCfgInfo[0].val, "value 1");
pCfgInfo[1].id = 2;
strcpy(pCfgInfo[1].val, "value 2");
FAKE_GLOBAL(getCfg);
WHEN_CALLED(getCfg(RET(&pCfgInfo))).Return(n);
//Act
CfgInfoType* cfgTest = NULL;
int result = getCfg(&cfgTest);
//Assert
Assert::AreEqual(result, n);
Assert::IsNotNull(cfgTest);
}
Hope it'll be useful for you!

Guidance Needed: Vectors of unique_ptr to dervied classes from an abstract base class

I'm trying to streamline my code and make it work better and easier:
This means diving into vectors and unique_ptr, about which I've read so many good things. However, they are entirely new to me. I have read a few pages on both, but its a lot to wrap my head around.
What I'm currently doing is creating objects of abstract class the traditional way:
VirtualBaseClass* foo1= new DerviedClass1;
VirtualBaseClass* foo2= new DerviedClass2;
VirtualBaseClass* foo3= new DerviedClass3;
But since I have 3 - and quite possibly will have lots more - I want to make it easier to switch between them because I'm going to be comparing any combination of the objects each program run.
Currently, to switch, I just rename the DerviedClass for which I want to instantiate an object so I don't have to go in renaming each foo1 with foo3, etc..
VirtualBaseClass* Generic1 = new DerviedClass3;
VirtualBaseClass* Generic2 = new DerviedClass1;
But ultimately I want the user to tell the program which two objects to compare. So a good starting point seems to make this an array of the VirtualBaseClass, but from research it seems like its pain to have to delete the arrays so people recommend using smart pointers and vectors.
So I tried to use both. For unique pointers I do
unique_ptr<vBaseClass*> foo1(DerviedClass1);
unique_ptr<vBaseClass*> foo2(DerviedClass2);
unique_ptr<vBaseClass*> geneic1 = move(foo1);
However, from what I read I should be doing
unique_ptr<vBaseClass*> foo1(new DerviedClass1);
but new gives error of type specfier but since it works without it I think nothing of it.
With move(foo1) I get an error no move for instance of overload function match and on compile a whole host of other errors such as
unique_ptr<vBaseClass*> champ1 = move(foo1);
error C3867: 'Controller::foo1': function call missing argument list; use '&Controller::foo1' to create a pointer to member
error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects 3 arguments - 1 provided
All this is being done in my Controller.h file btw.
I'm in desperate need of guidances. I don't know if what I'm doing is even neccsary, do I need to use vectors with this? How would I even begin too? Is there a better way of doing this? How do I even get the user to tell the program which object to use? With arrays it would be enter 0 for foo1 or enter 1 for foo2 but with vectors? Is there a better way?
My acutal code
#pragma once
#include "stdafx.h"
#include "Skarner.h"
#include "MasterYi.h"
#include "Riven.h"
using namespace std;
class Controller
{
public:
Controller();
~Controller();
double PCFreq;
__int64 CounterStart;
int CounterCheck;
ofstream out;
Champion* skarner = new Skarner;//old way of doing it
//Champion* yi = new MasterYi;//old way of doing it
//Champion* riven = new Riven;//old way of doing it
//Champion** champions = new Champion*[200];
//Champion[0] = new Skarner();
//unique_ptr<Champion> skarner(Skarner);
unique_ptr<Champion> yi(new MasterYi);// doesn't work new error
unique_ptr<Champion*> riven(Riven); //works with or without *
unique_ptr<Champion*> champ1 = move(riven)//error with move
vector<unique_ptr<Champion>> pChampions;//vector of pointers to champion
//unique_ptr<Champion> champ2;
//Champion *champ1 = dynamic_cast<Champion*>(yi);
//Champion *champ2 = dynamic_cast<Champion*>(skarner);//not sure what the signficance of this is
//Leaving some methods out
};
Wow so apparently you can't use the "new" in a header file only in the cpp file. However I'm still not sure how to make good use of it now that I have it declared in the controller.cpp? I really wanted it as a member variable/instance variable.
Trying to do this. in controller.h
shared_ptr<Champion> yi;
shared_ptr<Champion> riven;
shared_ptr<Champion> skarner;
shared_ptr<Champion> champ1;
shared_ptr<Champion> champ2;
and in the .cpp to define them
Controller::Controller()
{
PCFreq = 0.0;
CounterStart = 0;
out.open("finalStats.txt");
CounterCheck = 0;
yi = shared_ptr<Champion> (new MasterYi);
riven = shared_ptr<Champion>(new Riven);
skarner = shared_ptr<Champion>(new Skarner);
champ1 = move(yi);
champ2 = move(riven);
}
The above code now seems to work but I'm failing to see any direct benefits.
Explanation
You got a * to much:
unique_ptr<vBaseClass> foo1(new DerivedClass1);
should do the trick by allocating a new DerivedClass1 with dynamic storage duration and storing the pointer to it in foo1.
As a reminder, just read the type aloud: foo1has type "unique pointer to vBaseClass".
For the crowd in the comments
The following shows the difference in usage between a raw pointer and a unique pointer:
{
int* a = new int(42);
unique_ptr<int> b(new int(42));
std::cout << *a << ", " << *b << "\n";
delete a;
}
There is no further difference. Any further problem you have is related to a different problem that is hard to pinpoint without further information.
Also, unique_ptr<Champion*> riven(Riven); is a function declaration for a function by the name of riven returning a unique_ptr<Champion*> and taking a single argument of type Riven. The reason this does not error is because it does not do what you think it does at all.
Finally, there is absolutely nothing that makes headers anything special. In fact, C++ performs text substitution before parsing, so that the actual parser does not even know anything about where the code came from anymore!
Karmic Demonstration
Code:
struct champ { virtual std::string whoami() = 0; };
struct karma : champ { std::string whoami() override { return "karma"; } };
int main() {
champ* a = new karma;
std::unique_ptr<champ> b(new karma);
std::cout << a->whoami() << ", " << b->whoami() << "\n";
}
Result:
karma, karma
Proof
unique_ptr<Champion> yi(new MasterYi);// doesn't work new error looks like a function declaration to the compiler, and new isn't valid in that context.
unique_ptr<Champion*> riven(Riven); //works with or without * also looks like a function declaration and is valid with or without the *.
unique_ptr<Champion*> champ1 = move(riven)//error with move You can't move a function into a unique_ptr.
I'm having a really hard time understanding your question but maybe you mean something like this:
unique_ptr<Champion> yi = new MasterYi;
unique_ptr<Champion> riven = new Riven;
std::vector<std::unique_ptr<Champion> > pChampions = { new Skarner };

reduce code duplication using macros

I was wondering if someone out there could give me a pointer to reducing duplication when coding.
im required to call a function a number of times to populate a structure, for example:
typedef struct {
uint16_t u16_a;
bool b_org;
char* c_c;
uint16_t u16_d;
} TEntry;
I need to populate each value of these with a function call, although the return values vary, the same function is used for all.
Would a macro be sufficient to create a template in some way, so that the return type would be dependent on the specific parameter ("string")
for example:
Trrelevant::Trrelevant()
{
TPoint* u_apoint = Insufficient::FindValue("A");
if (u_bpoint != NULL) {
int a = u_apoint;
}
TPoint* p_apoint = Insufficient::FindValue("borg");
if (p_bpoint != NULL) {
bool b = p_bpoint;
}
TPoint* p_cpoint = Insufficient::FindValue("C");
if (etc != NULL) {
char* c = etc;
}
TEct* etc = Insufficient::FindValue("ETC");
if (etc != ETC) {
etc = etc;
}
TEntry entry = {a,
b,
c,
etc};
}
this code is not compiled or accurate, im just trying to illustrate. Im weak in C++ and new to macros, but would anyone know a way to have a macro solve this?
Thank you for your time
You could do something like this, although I don't know what it really buys you.
#define QuickFindValue(NAME, TYPE, FUNCTION) \
TYPE *NAME##Value = Insufficient::FindValue(#NAME); \
if (NAME##Value == NULL) { FUNCTION; }
You would use it like so:
QuickFindValue(C, TPoint, {
char *c = CValue;
// Do stuff..
});
Recently I had the same kind of issue, I'm not sure what kind of source you use for your inputs.
Personnaly, I used XML as input.
Then I have A Builder class that parses the XML call a factory funciton to build every struct in the c++ using the data from the parser.
I don't think that MACRO or templtes would be of any help (or it would be a bad solution).
Note that an external resource (like xml) is nice if ever you want to change without recompiling.
Best

luabind: cannot retrieve values from table indexed by non-built-in classes‏

I'm using luabind 0.9.1 from Ryan Pavlik's master distribution with Lua 5.1, cygwin on Win XP SP3 + latest patches x86, boost 1.48, gcc 4.3.4. Lua and boost are cygwin pre-compiled versions.
I've successfully built luabind in both static and shared versions.
Both versions pass all the tests EXCEPT for the test_object_identity.cpp test which fails in both versions.
I've tracked down the problem to the following issue:
If an entry in a table is created for NON built-in class (i.e., not int, string, etc), the value CANNOT be retrieved.
Here's a code piece that demonstrates this:
#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/detail/debug.hpp>
using namespace luabind;
struct test_param
{
int obj;
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def_readwrite("obj", &test_param::obj)
];
test_param temp_object;
object tabc = newtable(L);
tabc[1] = 10;
tabc[temp_object] = 30;
TEST_CHECK( tabc[1] == 10 ); // passes
TEST_CHECK( tabc[temp_object] == 30 ); // FAILS!!!
}
tabc[1] is indeed 10 while tabc[temp_object] is NOT 30! (actually, it seems to be nil)
However, if I use iterate to go over tabc entries, there're the two entries with the CORRECT key/value pairs.
Any ideas?
BTW, overloading the == operator like this:
#include <luabind/operator.hpp>
struct test_param
{
int obj;
bool operator==(test_param const& rhs) const
{
return obj == rhs.obj;
}
};
and
module(L)
[
class_<test_param>("test_param")
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
Doesn't change the result.
I also tried switching to settable() and gettable() from the [] operator. The result is the same. I can see with the debugger that default conversion of the key is invoked, so I guess the error arises from somewhere therein, but it's beyond me to figure out what exactly the problem is.
As the following simple test case show, there're definitely a bug in Luabind's conversion for complex types:
struct test_param : wrap_base
{
int obj;
bool operator==(test_param const& rhs) const
{ return obj == rhs.obj ; }
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def(constructor<>())
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
object tabc, zzk, zzv;
test_param tp, tp1;
tp.obj = 123456;
// create new table
tabc = newtable(L);
// set tabc[tp] = 5;
// o k v
settable( tabc, tp, 5);
// get access to entry through iterator() API
iterator zzi(tabc);
// get the key object
zzk = zzi.key();
// read back the value through gettable() API
// o k
zzv = gettable(tabc, zzk);
// check the entry has the same value
// irrespective of access method
TEST_CHECK ( *zzi == 5 &&
object_cast<int>(zzv) == 5 );
// convert key to its REAL type (test_param)
tp1 = object_cast<test_param>(zzk);
// check two keys are the same
TEST_CHECK( tp == tp1 );
// read the value back from table using REAL key type
zzv = gettable(tabc, tp1);
// check the value
TEST_CHECK( object_cast<int>(zzv) == 5 );
// the previous call FAILS with
// Terminated with exception: "unable to make cast"
// this is because gettable() doesn't return
// a TRUE value, but nil instead
}
Hopefully, someone smarter than me can figure this out,
Thx
I've traced the problem to the fact that Luabind creates a NEW DISTINCT object EVERY time you use a complex value as key (but it does NOT if you use a primitive one or an object).
Here's a small test case that demonstrates this:
struct test_param : wrap_base
{
int obj;
bool operator==(test_param const& rhs) const
{ return obj == rhs.obj ; }
};
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<test_param>("test_param")
.def(constructor<>())
.def_readwrite("obj", &test_param::obj)
.def(const_self == const_self)
];
object tabc, zzk, zzv;
test_param tp;
tp.obj = 123456;
tabc = newtable(L);
// o k v
settable( tabc, tp, 5);
iterator zzi(tabc), end;
std::cerr << "value = " << *zzi << "\n";
zzk = zzi.key();
// o k v
settable( tabc, tp, 6);
settable( tabc, zzk, 7);
for (zzi = iterator(tabc); zzi != end; ++zzi)
{
std::cerr << "value = " << *zzi << "\n";
}
}
Notice how tabc[tp] first has the value 5 and then is overwritten with 7 when accessed through the key object. However, when accessed AGAIN through tp, a new entry gets created. This is why gettable() fails subsequently.
Thx,
David
Disclaimer: I'm not an expert on luabind. It's entirely possible I've missed something about luabind's capabilities.
First of all, what is luabind doing when converting test_param to a Lua key? The default policy is copy. To quote the luabind documentation:
This will make a copy of the parameter. This is the default behavior when passing parameters by-value. Note that this can only be used when passing from C++ to Lua. This policy requires that the parameter type has an accessible copy constructor.
In pratice, what this means is that luabind will create a new object (called "full userdata") which is owned by the Lua garbage collector and will copy your struct into it. This is a very safe thing to do because it no longer matters what you do with the c++ object; the Lua object will stick around without really any overhead. This is a good way to do bindings for by-value sorts of objects.
Why does luabind create a new object each time you pass it to Lua? Well, what else could it do? It doesn't matter if the address of the passed object is the same, because the original c++ object could have changed or been destroyed since it was first passed to Lua. (Remember, it was copied to Lua by value, not by reference.) So, with only ==, luabind would have to maintain a list of every object of that type which had ever been passed to Lua (possibly weakly) and compare your object against each one to see if it matches. luabind doesn't do this (nor do I think should it).
Now, let's look at the Lua side. Even though luabind creates two different objects, they're still equal, right? Well, the first problem is that, besides certain built-in types, Lua can only hold objects by reference. Each of those "full userdata" that I mentioned before is actually a pointer. That means that they are not identical.
But they are equal, if we define an __eq meta operation. Unfortunately, Lua itself simply does not support this case. Userdata when used as table keys are always compared by identity, no matter what. This actually isn't special for userdata; it is also true for tables. (Note that to properly support this case, Lua would need to override the hashcode operation on the object in addition to __eq. Lua also does not support overriding the hashcode operation.) I can't speak for the authors of Lua why they did not allow this (and it has been suggested before), but there it is.
So, what are the options?
The simplest thing would be to convert test_param to an object once (explicitly), and then use that object to index the table both times. However, I suspect that while this fixes your toy example, it isn't very helpful in practice.
Another option is simply not to use such types as keys. Actually, I think this is a very good suggestion, since this kind of light-weight binding is quite useful, and the only other option is to discard it.
It looks like you can define a custom conversion on your type. In your example, it might be reasonable to convert your type to a Lua number which will behave well as a table index.
Use a different kind of binding. There will be some overhead, but if you want identity, you'll have to live with it. It sounds like luabind has some support for wrappers, which you may need to use to preserve identity:
When a pointer or reference to a registered class with a wrapper is passed to Lua, luabind will query for it's dynamic type. If the dynamic type inherits from wrap_base, object identity is preserved.