samedi 1 mai 2021

Why the new keyboard don't work at dev c++

Some buttons on my keyboard do not work, and for solve this problem I am installed keyextender and key remapper, and the both applications work, but when I tried to write in dev c++ all modifications in keyextender and key remapper doesn't work Please help me

Interesting extra destruction call during push_back in std::vector

I find the output of the following code very interesting.

class Name
{
  string _name;
public:
  Name(const string& name) : _name(name) { cout << "ctor of " << _name << endl; }
  ~Name(){ cout << "dtor of " << _name << endl; }
};
int main() {

  vector<Name> list;
  cout << "------------------START push_back" << endl;
  list.push_back(Name(string("A")));
  cout << "------------------push_back(A) performed..." << endl;
  list.push_back(Name(string("B")));
  cout << "------------------push_back(B) performed..." << endl;
  list.push_back(Name(string("C")));
  cout << "------------------push_back(C) performed..." << endl;
  cout << "------------------END push_back" << endl;

  return 0;
}

I can understand that push_back uses an extra temporary object which is why emplace_back is recommended for better performance. Can someone explain the extra destructor calls shown in the output below with (???) next to it.

------------------START push_back
ctor of A
dtor of A
------------------push_back(A) performed...
ctor of B
dtor of A(???)
dtor of B
------------------push_back(B) performed...
ctor of C
dtor of A(???)
dtor of B(???)
dtor of C
------------------push_back(C) performed...
------------------END push_back
dtor of A
dtor of B
dtor of C
------------------START emplace_back
ctor of A
------------------emplace_back(A) performed...
ctor of B
------------------emplace_back(B) performed...
ctor of C
------------------emplace_back(C) performed...
------------------END emplace_back()
dtor of A
dtor of B
dtor of C

How to mock a function called in the constructor of a RAII class

Is there a way to correctly mock a function call which is used inside a constructor using Google Mock / Google Test? This for unit testing my RAII class.

What I tried is creating a Mock class which inherits from the implementation and have the MOCK_METHODx functions in place. Then in my test suite I want to put the EXPECT_CALL before the creation of the object, however, for the EXPECT_CALL the object already needs to be created.

// DeviceImpl.h
class DeviceImpl : public IDevice {
public: 
    explicit DeviceImpl(uint32_t deviceAddress);
    ~DeviceImpl() override;

    uint32_t read();
    void write(uint32_t data);

protected:
    /* Virtual forwarding functions to make gmock happy */
    virtual int _open_device(uint32_t deviceAddress) {
      return open_device(deviceAddress); // this is a C function
    }
    virtual int _close_device(int fd) {
      return close_device(fd); // this is a C function
    }
}

// DeviceImplMock.h
class DeviceImplMock : public DeviceImpl {
public:
    DeviceImplMock() : DeviceImpl(1) {};
    ~DeviceImplMock() override = default;

    MOCK_METHOD1(_open_device, int(uint32_t deviceAddress));
    MOCK_METHOD1(_close_device, int(int));
}

// DeviceTest.cc
class DeviceTestSuite : public ::testing::Test {
public:
    std::shared_ptr<DeviceImplMock> device_{nullptr};

    DeviceTestSuite() {
        // Determine how to fix the order problem.
        // For the EXPECT_CALL, and thus the mock, the objects already needs to be created.
        // However, creating the object (with std::make_shared) already calls the non-mocked function
        // What to do here?
        EXPECT_CALL(*device_.get(), _open_device(::testing::_)).WillOnce(Return(1));
        device_ = std::make_shared<DeviceImplMock>();
    }

    ~DeviceTestSuite() override {
        EXPECT_CALL(*device_.get(), _close_device(1)).WillOnce(Return(0));
    }
};

TEST_F(DeviceTestSuite, read) {
  // Test for device->read() here, etc...
}

Examples on how to unit test RAII classes using GMock are extremely welcome.

Roy

how to assign the enum values to strings using map in C++

I have a map with string and enum. I am getting an enum value as input and from that I need to get a string.

Below is the code snippet I have written for that:

std::map<std::string, Messages> m_MessagesMap;

auto MessageID = GetMessageID();
GetStringFromEnum(MessageID);
std::string CJsonMessageUtil::GetStringFromEnum(Messages l_eMessages)
{
    for (auto it = m_MessagesMap.begin(); it != m_MessagesMap.end(); ++it)
    {
        if (it->second == l_eMessages)
            return it->first;
    }

    return "";
}

This way it is working. But every time it is looping through all the items in the map. Is there any better way to map enums to strings?

How to deal with "not covariant" errors in paired hierarchies (C++)

Suppose I want a class Team to have a virtual get_player member which is implemented by FootballTeam and RugbyTeam, and that these implementations return the covariant types FootballPlayer and RugbyPlayer.

Suppose I also want Player to have a virtual get_team member which is implemented by FootballPlayer and RugbyPlayer, and that these implementations return the covariant types FootballTeam and RugbyTeam.

Is it possible to implement this pattern? I've tried, but, when overriding the get_player member of Team, I'm getting the error: "Return type of virtual function 'get_player' is not covariant with the return type of the function it overrides".

I can't define the Player hierarchy first, because then I'd have the same problem but the other way around!

class Player;
class FootballPlayer;
class RugbyPlayer;

class Team {
  virtual Player &get_player() = 0;
};
class FootballTeam : public Team {
  FootballPlayer &get_player() override; // error here
};
class RugbyTeam : public Team {
  RugbyPlayer &get_player() override; // error here
};

class Player {
  virtual Team& get_team() = 0;
};
class FootballPlayer : public Player {
  FootballTeam& get_team() override;
};
class RugbyPlayer : public Player {
  RugbyTeam& get_team() override;
};

Using std::conditional with iterator

In "Mastering the C++17 STL" book I saw both iterator and const_iterator implementation in one class using conditional for less code duplication

Here's my implementation for simple array class (most code for array class is skipped):

template<class T, size_t N>
class Array
{
public:
    template<bool Const>
    class ArrayIterator {
        friend class Array;
    public:
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = std::conditional<Const, const value_type*, value_type*>;
        using reference = std::conditional<Const, const value_type&, value_type&>;
        using iterator_category = std::random_access_iterator_tag;

        reference operator*() const { return *ptr; }
        ArrayIterator<Const>& operator++() { ++ptr; return *this; }
        ArrayIterator<Const> operator++(int) { auto res = *this; ++(*this); return res; }

        template<bool R>
        bool operator==(const ArrayIterator<R>& iter) const { return ptr == iter.ptr; }
        template<bool R>
        bool operator!=(const ArrayIterator<R>& iter) const { return ptr != iter.ptr; }

    private:
        explicit ArrayIterator(pointer p) : ptr(p) {};
        pointer ptr;
    };

    using iterator = ArrayIterator<false>;
    using const_iterator = ArrayIterator<true>;
    iterator begin() { return iterator(data); }
    iterator end() { return iterator(data + N); }
    const_iterator cbegin() const { return const_iterator(data); }
    const_iterator cend() const { return const_iterator(data + N); }

private:
    T* data;
};

This code compiles with no errors, but iterator is kinda unusable:

Array<int, 100> arr;
/*filling it with numbers*/
int x = *arr.begin(); 

Gives error:

main.cpp:9:9: error: no viable conversion from 'Array<int, 100>::ArrayIterator<false>::reference' (aka 'conditional<false, const int &, int &>') to 'int'

How can I use that iterator or should I just abandon this idea from book?

Error:sorry, unimplemented: string literal in function template signature while Using decltype in function template

Hi i am trying to understand how templates work and trying out different examples. I am getting an error while executing the code below. First i am writing the code and then will write what i think is happening.

Code snippet 1:

#include <iostream>
#include<vector>
#include<string>

template<typename It>
auto fcn(It beg, It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
    
    return *beg;
}
int main()
{   
    std::vector<std::string> stringVector = {"firstElement","secondElement"};
    std::vector<std::string>::iterator beg = stringVector.begin();
    
    decltype(*beg + "k") l = "anothername";//this is okay and is working here.
    
    
    std::string s = fcn(stringVector.begin(), stringVector.end());
   
  
   return 0;
}

While compiling/executing snippet 1 i get an error.

sorry, unimplemented: string literal in function template signature auto fcn(It beg, It end) -> decltype(*beg +"name"){

Here is my explanation of what is happening: The return type of the function template fcn will be deduced from the expression decltype(*beg + "name"). So *beg is a reference to the element and in our case *beg is a reference to string that is string& and then *beg + "name" is a rvalue string. So decltype(*beg + "name") will give us a type string. But inside the definition of the function template fcn we are returning string& and therefore the return type of the function(string) and the type of the value returned from the function(string&) does not match and we get the error. But now as in the 2nd Code snippet i replace return *beg; with std::string temp = "name"; return temp; the return type and the type of the returned value should match. The problem is in the 2nd case i am still getting an error. Why am i getting this error and how can i resolve this? Also is my explanation of what is going on correct?

Code Snippet 2:

auto fcn(It beg, It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
    std::string temp = "name";
    return temp;
}