I'm currently trying to implement a class around a valarray object and i get a exception when trying to run:
class TestClass
{
public:
valarray<int> va;
TestClass() { va.resize(5, 1); }
slice_array<int>& get_slice()
{
return va[slice(0, 3, 2)];
}
};
//In main():
TestClass obj;
slice_array<int>& ref = obj.va[slice(0,3,2)];
ref = -1; //OK
obj.get_slice() = -1; //Throws exception
Aren't the two assignments the same thing?
I solved it myself:
It seems that a valarray[slice(int, int, int)] is not an lvalue or is temporary, so it's not allowed to initialize a reference with such an object (oddly enough, VS2012 allows to do so in some cases).
Related
The crux of the issue is I want to create a vector of base pointers to reference children objects. However I'm having issues accessing the methods of the children. I've seen examples of downcasting online but I don't feel it's the best thing for me since I want to keep my code generic. Please look below for a sample of what I'm trying to accomplish.
class Base
{
public:
stuffx;
private:
stuffy;
}
template<typename U>
class Child : public Base
{
public:
Child(
std::function<U()> getterFunc,
std::function<void(U)> setterFunc
):
mgetter(getterFunc),
msetter(setterFunc)
{
}
U getFunction() const {return m_getter();}
void setFunction(U input) const {return m_setter(input);}
private:
observableValues() {}
std::function<U()> m_getter;
std::function<void(U)> m_setter;
}
int main()
{
std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..), std::bind(...)),
std::make_shared<Child<string>> (std::bind(..), std::bind(...)) };
Dummy.at(0)->getGFunction(); // this throws an error as out of scope.
(dynamic_cast<Child<int>>(Dummy.at(0))->getGFunction(); // this is ok
}
In this example above my vector is of size 2 which is manageable but my goal is to serialize c++ classes to a psql server and may have to handle vectors of size 30+. My next question is is there a way to automate this in a for loop taking into the account the type deduction that may need to be performed for typename U.
int main()
{
std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..), std::bind(...)),
std::make_shared<Child<string>> (std::bind(..), std::bind(...)) };
std::vector<std::shared_ptr<Base>>::const_iterator it_base = Dummy.begin();
for (; it_base != Dummy.end(); ++it_base)
{
//insert method here for downcasting
}
}
I am facing problem while running gtest for the following code sample.
ignore header includes as its compilable and running fine.
Error:
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: receive(0x7ffcee4fc990, 0x7ffcee4fc900)
Returns: 0
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#knowing-when-to-expect for details.
/data/home/sipadhy/unit_test_research/gTest/ImplClassTest.cpp:174: Failure
Actual function call count doesn't match EXPECT_CALL(mockImplClass, receive(_, _))...
Expected: to be called at least once
Actual: never called - unsatisfied and active
Sample Code:
// Main Class where function to be mocked
class ImplClass
{
public:
virtual int receive(structX* x, structY* y){ // some logic }
};
// An intermidiate class which calls the main class
class IntermidiateClass
{
std::shared_ptr<ImplClass> implClassPtr = nullptr;
public:
setImplClassptr(std::shared_ptr<ImplClass> ptr)
{
implClassPtr = ptr;
}
int getValue()
{
structX x;
structY y;
return(implClassPtr->receive(x, y));
}
};
// Mock Class
class MockImplClass: public ImplClass
{
public:
MOCK_METHOD2(receive, int(structX, structY));
}
// Test case
TEST(MyTest, TEST1)
{
MockImplClass mockImplClass;
IntermidiateClass intermidiateObj;
intermidiateObj.setImplClassptr(std::make_shared<MockImplClass>());
EXPECT_CALL(mockImplClass, receive(_, _))
.Times(AtLeast(1))
.WillRepeatedly(Return(1));
int retVal = intermidiateObj.getValue();
}
Thanks,
Siva
You create a brand new object of the MockImplClass class here:
std::make_shared<MockImplClass>()
Thus your first created object
MockImplClass mockImplClass;
never gets used to call receive()
How do I create a reference to immutable classes, but while keeping the ability to reassign the reference, sort of like string?
import std.stdio;
immutable class Test {
string test(){
return "test";
}
}
void main(){
auto test = new Test;
writeln(test.test);
}
This causes an error, because the created instance is not immutable:
test.d(14): Error: immutable method test.Test.test is not callable using a mutable object
new immutable doesn't work either, because the resulting variable cannot be assigned a new one afterwards.
immutable(Test)* would work, but is there a way avoiding pointers?
Use std.typecons.Rebindable http://dpldocs.info/experimental-docs/std.typecons.Rebindable.html#examples
import std.typecons;
class Widget { int x; int y() const { return x; } }
auto a = Rebindable!(const Widget)(new Widget);
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// Fine
a = new Widget;
You can use immutable in the same way of auto to infer types:
immutable test = new Test;
immutable other_test = test;
I am writting a little ruby module with some very simple classes in C:
typedef struct window_t {
GtkWidget * widget;
}
static void c_window_struct_free(window_t *c)
{
if(c)
{
ruby_xfree(c);
}
}
static VALUE c_window_struct_alloc( VALUE klass)
{
return Data_Wrap_Struct(klass, NULL, c_window_struct_free,ruby_xmalloc(sizeof(window_t)));
}
VALUE c_window = rb_define_class_under(m_rtortosa, "Window", c_widget)
rb_define_method(c_window, "set_title",RUBY_METHOD_FUNC(window_set_title), 1);
//For each class I don't rewritte any "new" or "initialize" function. I let the default
When my module is initialized, a gtk window is created, and I have a ruby method for this module that call:
static VALUE rtortosa_window(VALUE self)
{
VALUE win;
VALUE m_rtortosa = rb_const_get( rb_cObject, rb_intern( "Rtortosa" ) );
VALUE cWindow = rb_const_get_at( m_rtortosa, rb_intern("Window") );
win = rb_class_new_instance(0, NULL, backbone.rb_objects.cWindow);
window_t *w;
Data_Get_Struct(win,window_t, w);
w->widget = backbone.window.widget;
return win;
}
The problesm occurs when I call the rtortosta_window from ruby, it throws an error like this :
wrong argument type Rtortosa::Window (expected Data) (TypeError)
After investigations this message is comming from the Data_Get_Struct function.
I don't see what I am doing wrong, I have a notebook class that is written in the same way but it works as expected.
I have forgotten to bind the alloc function to the class:
rb_define_alloc_func(c_window, c_window_struct_alloc);
I'm writing a simple, lightweight engine in D. For the input calls I use GLFW3. The library in question uses callbacks to send input events to the program.
What I would like is to use a method from a class as the callback function, rather than a function. This is proving difficult (just as it is in C++). I believe there is an elegant way to do it, but this is how I got it right now.
public void initialise(string logPath) {
[...]
m_Window = new RenderWindow();
m_Window.create();
// Lets set up the input loop.
GLFWkeyfun keyCB = function(GLFWwindow* win, int key, int scancode, int action, int mods) {
printf("Got key event: %d:%d:%d:%d\n");
RenderWindow rw = Root().getRenderWindow();
switch (key) {
case KeyboardKeyID.Q:
glfwSetWindowShouldClose(win, true);
break;
case KeyboardKeyID.H:
if (rw.hidden) {
rw.show();
} else {
rw.hide();
}
break;
default:
break;
}
};
glfwSetKeyCallback(m_Window.window, keyCB);
}
Here is the definition of the callback setting function and type:
extern (C) {
alias GLFWkeyfun = void function(GLFWwindow*, int, int, int, int);
GLFWkeyfun glfwSetKeyCallback(GLFWwindow*, GLFWkeyfun);
}
What I would like to do instead, is create a method that is part of the class. Is there any way to do this?
A solution I tried was a static method wrapped around in extern (C), this worked for calling it, but then I could (obviously) not access this or any other methods, which defeats the point of the exercise.
Thanks in advance.
The way I'd do it is to have a static map of the pointers to the class, so like:
static YourWindowClass[GLFWwindow*] mappings;
Then, in the constructor, once you get a GLFWwindow pointer, add it right in:
mappings[m_Window.window] = this;
Now, make the static extern(C) function to use as the callback. When it gets a pointer from C, look up your class reference in that mappings array and then go ahead and call the member function through that, forwarding the arguments.
So a bit of an extra step, but since it doesn't look like the callback lets you pass user-defined data to it (BTW, attention all lib writers: user-defined void* to the callbacks is sooooo useful, you should do it whenever possible!), but since it doesn't do that the associative array is the next best thing.
Well, I have figured it out my own. The solution I went with was a Singleton class InputManager. Instances of RenderWindow attach themselves to it with the following function. The InputManager then creates an anonymous function() for the RenderWindow that receives events, which then calls a function that handles the actual event.
The idea is then that listeners attach themselves to the InputManager and receive keyboard events for the RenderWindow they requested.
class InputManager {
private static InputManager m_Instance;
private RenderWindow[] m_Watched;
private KeyboardListener[][RenderWindow] m_KeyListeners;
public void recvKeyEvent(GLFWwindow* w, int k, int c, int a, int m) {
writeln("Received key: ", k);
}
public void watch(RenderWindow win) {
if (!isWatched(win)) {
// Relay the key callbacks onto the InputManager.
GLFWkeyfun keyCB = function(GLFWwindow* w, int k, int c, int a, int m) {
InputManager().recvKeyEvent(w, k, c, a, m);
};
glfwSetKeyCallback(win.window, keyCB);
}
}
private bool isWatched(RenderWindow win) {
foreach(RenderWindow w; m_Watched) {
if (win == w) {
return true;
}
}
return false;
}
public static InputManager opCall() {
if (m_Instance is null) {
m_Instance = new InputManager();
}
return m_Instance;
}
private this() {
// nothing
}
}
Works like a charm, now to figure out how to properly attach listeners elegantly.
For those curious, the full source code with how this is set up can be found at https://github.com/Adel92/Mage2D. I hope it helps someone else in a similar position with callbacks.