Function move could not be resolved, Semantic Error - c++11

The following program which is supposed to emulate std::vector. I am using Eclipse IDE for C/C++ Developers
Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500
and my c++ version is g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
is flagging error that "function std::move could not be resolved".
What is the possible reason for this error ?
//============================================================================
// Name : data_structure_1.cpp
// Author : Manish Sharma
// Description : Programme to implement a simple vector class named "Vector".
// Reference : Data Structures and Algo. analysis in c++, Mark Allen Weiss
//============================================================================
#include <iostream>
#include <algorithm>
using namespace std;
template<class Object>
class Vector{
public:
// constructor
explicit Vector(int initSize = 0):
theSize{initSize},
theCapacity{initSize + SPARE_CAPACITY},
objects{new Object[theCapacity]}{
}
// copy constructor
Vector(const Vector& rhs):
theSize{rhs.theSize},
theCapacity{rhs.theCapacity},
objects{new Object[theCapacity]}{
for(int k = 0;k<theSize; ++k){
objects[k] = rhs.objects[k];
}
}
// copy assignment operaor
Vector & operator= (const Vector & rhs){
Vector copy = rhs;
std::swap(*this,copy);
return *this;
}
//class destructor
~Vector(){
delete[] objects;
}
//c++ 11 additions, reference to rvalues
Vector(Vector&& rhs) :
theSize{rhs.theSize},
theCapacity{rhs.theCapacity},
objects{rhs.objects}{
cout<<endl<<"Inside lvalue reference constructor";
//if you forget to include this then when rhs will you destroyed
//you will be left with a dangling pointer
rhs.objects = nullptr;
rhs.theSize = 0;
rhs.theCapacity = 0;
}
// copy assignment operaor
Vector & operator= (Vector && rhs){
cout<<endl<<"Inside lvalue reference copy";
Vector copy = rhs;
std::swap(*this,copy);
return *this;
}
void resize(int newSize){
if(newSize > theCapacity)
reserve(newSize*2);
theSize = newSize;
}
void reserve(int newCapacity){
if(newCapacity<theSize)
return;
Object *newArray = new Object[newCapacity];
cout<<endl<<"moving inside reserve";
for(int k=0;k<theSize;++k){
newArray[k] = std::move(objects[k]);
}
theCapacity = newCapacity;
std::swap(objects,newArray);
delete[] newArray;
}
//Some extra useful functions
int size() const{
return theSize;
}
bool empty() const{
return size()==0;
}
int capacity() const{
return theCapacity;
}
void increaseCapacity(){
reserve(2*theCapacity+1);
}
//insertion and deletion functions
void push_back(const Object & x){
if(theSize == theCapacity){
increaseCapacity();
}
cout<<endl<<"Moving inside push_back";
objects[theSize++] = std::move(x);
}
void pop_back(){
--theSize;
}
using iterator = Object*;
using const_iterator = const Object*;
iterator begin(){
return &objects[0];
}
const_iterator begin() const{
return &objects[0];
}
iterator end(){
return &objects[size()];
}
const_iterator end() const{
return &objects[size()];
}
//class specific constants
static const int SPARE_CAPACITY = 16;
private:
int theSize;
int theCapacity;
Object * objects;
};
int main() {
Vector<int> my_vector;
my_vector.push_back(10);
int j{24};
my_vector.push_back(j);
for(int i = 0;i<20;i++){
my_vector.push_back(i*10);
}
cout<<"\nSize = "<<my_vector.size()<<endl;
my_vector.capacity();
for(auto it = my_vector.begin();it!=my_vector.end();++it){
cout<<*it<<", ";
}
return 0;
}

Related

Error in storing outer class object in inner class C++

I was implementing the ring buffer and have encountered an error. What does it mean to store a reference of outer class(class ring) object(m_ring) in inner class(class iterator) and when I remove the reference(&) the program compiles correctly but crashes. Please explain what is happening.(See the comment in Ring.h) Sorry for bad English.
// Ring.h
#ifndef RING.H
#define RING.H
#include <iostream>
using namespace std;
template<class T>
class ring {
unsigned int m_size;
int m_pos;
T *m_values;
public:
class iterator;
public:
ring(unsigned int size) : m_size(size), m_pos(0)
{
m_values = new T[m_size];
}
~ring()
{
delete[] m_values;
}
void add(const T &val)
{
m_values[m_pos] = val;
m_pos++;
m_pos %= m_size;
}
T& get(int pos)
{
return m_values[pos];
}
iterator begin()
{
return iterator(0, *this);
}
iterator end()
{
return iterator(m_size, *this);
}
};
template<class T>
class ring<T>::iterator {
int m_pos;
ring &m_ring; // Removing & gives garbage output.
public:
iterator(int pos, ring& aRing) : m_pos(pos), m_ring(aRing){}
bool operator!=(const iterator &other) const
{
return other.m_pos != m_pos;
}
iterator &operator++(int)
{
m_pos++;
return *this;
}
iterator &operator++()
{
m_pos++;
return *this;
}
T &operator*()
{
// return m_ring.m_values[m_pos];
return m_ring.get(m_pos);
}
};
#endif // RING
Driver program :
// Ring_Buffer_Class.cpp
#include <iostream>
#include "ring.h"
using namespace std;
int main()
{
ring<string> textring(3);
textring.add("one");
textring.add("two");
textring.add("three");
textring.add("four");
// C++ 98
for(ring<string>::iterator it = textring.begin(); it != textring.end(); it++)
{
cout << *it << endl;
}
cout << endl;
// C++11
for(string value : textring)
{
cout << value << endl;
}
return 0;
}
I also observed that removing ~ring() (Destructor) results into correct output.
Expected output :
four
two
three
four
two
three

Implementing custom iterator to work with std::sort

My aim is to learn how to write a custom iterator from scratch. I have written the following iterator:
#include <iterator>
template<class D>
class SpanIterator final : public std::iterator<std::random_access_iterator_tag, D>
{
private:
D* _data;
public:
explicit SpanIterator(D* data) :
_data{ data }
{
}
SpanIterator(const SpanIterator& itertator) = default;
SpanIterator& operator=(const SpanIterator& iterator) = default;
SpanIterator& operator=(D* data)
{
_data = data;
return *this;
}
operator bool() const
{
return _data != nullptr;
}
bool operator==(const SpanIterator& itertator) const
{
return _data == itertator._data;
}
bool operator!=(const SpanIterator& itertator) const
{
return _data != itertator._data;
}
SpanIterator& operator+=(const std::ptrdiff_t& movement)
{
_data += movement;
return *this;
}
SpanIterator& operator-=(const std::ptrdiff_t& movement)
{
_data -= movement;
return *this;
}
SpanIterator& operator++()
{
++_data;
return *this;
}
SpanIterator& operator--()
{
--_data;
return *this;
}
SpanIterator operator++(int)
{
auto temp = *this;
++_data;
return temp;
}
SpanIterator operator--(int)
{
auto temp = *this;
--_data;
return temp;
}
SpanIterator operator+(const std::ptrdiff_t& movement)
{
auto oldPtr = _data;
_data += movement;
auto temp = *this;
_data = oldPtr;
return temp;
}
SpanIterator operator-(const std::ptrdiff_t& movement)
{
auto oldPtr = _data;
_data -= movement;
auto temp = *this;
_data = oldPtr;
return temp;
}
D& operator*()
{
return *_data;
}
const D& operator*() const
{
return *_data;
}
D& operator->()
{
return _data;
}
};
Which I am testing like so:
#include <iostream>
#include <array>
int main()
{
std::array<double, 3> values = { 1, 2, 1 };
SpanIterator<double> begin{ values.data() };
SpanIterator<double> end{ values.data() + values.size() };
std::sort(begin, end);
return EXIT_SUCCESS;
}
However it fails to compile, giving the following errors:
Error C2666 'SpanIterator::operator -': 2 overloads
Error C2780 'void std::_Sort_unchecked1(_RanIt,_RanIt,_Diff,_Pr &)':
expects 4 arguments - 3 provided
If I remove SpanIterator operator-(const std::ptrdiff_t& movement) I get different errors:
'void std::_Guess_median_unchecked(_RanIt,_RanIt,_RanIt,_Pr &)':
could not deduce template argument for '_RanIt' from 'int'
'_Guess_median_unchecked': no matching overloaded function found
Error C2100 illegal indirection
You're missing operators to support the following operations (where a and b are values of your iterator type SpanIterator<...>):
b - a
a < b (and the remaining comparisons, although most implementations of std::sort don't use them).
For example, you could provide the following member operator overloads:
std::ptrdiff_t operator-(SpanIterator const&) const;
bool operator<(SpanIterator const&) const;
// etc.
(Note that non-member overloads are often preferred: Operator overloading)
In addition, your operator bool should be explicit to avoid ambiguous overloads for the a + n, n + a and b - a operations (where n is a value of your difference type i.e. std::ptrdiff_t).

lambda function in c++ and inheritance

i'm new to lambda functions in c++ and am trying to make a simple one but have some problems. i've tried to make a heterogeneous container which include stacks, queues, and lists and one of the exercise is to make a lambda function which check if an element answers a specific condition defined as:
using Condition = bool (*)(T const&);
so here is a piece of my heterogeneous container:
For example for stacks:
template <typename T>
using Condition1 = bool (*)(T const&);
template <typename T>
class LinkedStack {
private:
StackElement<T>* top;
public:
LinkedStack();
LinkedStack(LinkedStack const&);
LinkedStack& operator=(LinkedStack const&);
bool empty() const;
bool member(T const& x);
T peek() const;
void push(T const&);
T pop();
~LinkedStack();
};
template<typename T,typename Condition1>
bool q_filter(Condition1 func,LinkedStack<T>& s){
LinkedStack<T> tmp;
tmp = s;
if((tmp).empty())
return false;
while(!tmp.empty()){
if (func(tmp.peek()))
return true;
else
tmp.pop();
}
return false;
}
the stack-object(which is need to perform object in h-container):
template <typename T>
class Object {
public:
using Condition = bool (*)(T const&);
virtual bool insert(T const&) = 0;
virtual bool remove(T&) = 0;
virtual bool member(T const&) = 0;
virtual int l_size() = 0;
virtual void sort() = 0;
virtual bool special_condition(Condition);
virtual void print(ostream& os) const = 0;
virtual ~Object() {}
};
template <typename T>
class StackObject : public Object<T>, private LinkedStack<T> {
public:
using Condition = bool (*)(T const&);
// включване
bool insert(T const& x) {
LinkedStack<T>::push(x);
return true;
}
// изключване
bool remove(T& x) {
if (LinkedStack<T>::empty())
return false;
x = LinkedStack<T>::pop();
return true;
}
// проверка
bool member(T const& x){
return LinkedStack<T>::member(x);
}
int l_size() {
return my_size(*this);
}
// извеждане
void print(ostream& os) const {
os << *this;
}
void sort(){
s_sort(*this);
}
bool special_condition(Condition c){
return q_filter(c,*this);
}
};
and main-function:
int main(){
QueueStackList qsl;
qsl.read_from_file();
(*(qsl.begin()))->special_condition([](int x) -> bool { return x%2 != 0; });
return 0;
}
QueueStackList is implemented like a linked-list and qsl.begin() returns
an iterator for the first element in the heterogeneous list;
when i compile it returns this kind of errors:
invalid user-defined conversion from 'main()::<lambda(int)>' to 'Object<int>::Condition {aka bool (*)(const int&)}' [-fpermissive]|
candidate is: main()::<lambda(int)>::operator bool (*)(int)() const <near match>|
no known conversion for implicit 'this' parameter from 'bool (*)(int)' to 'Object<int>::Condition {aka bool (*)(const int&)}'|
which i really don't know what mean ?

boost graph library adjacency_list: maintain EdgeList sorted by EdgeProperties

I'm trying to use a std::multiset container with strict weak ordering on the EdgeProperties for the EdgeList template parameter of boost::adacency_list
namespace boost {
struct propOrderedMultisetS { };
template <class ValueType>
struct container_gen<propOrderedMultisetS,ValueType> {
struct less {
bool operator() (const ValueType& lhs, const ValueType& rhs) const {
return (lhs.get_property() < rhs.get_property());
};
};
typedef std::multiset<ValueType, less> type;
};
struct MyVertexProp { int v; };
struct MyEdgeProp {
bool operator<(const MyEdgeProp& rhs) const {
return this->weight < rhs.weight;
}
double weight;
}
typedef adjacency_list<listS, listS, undirectedS, MyVertexProp, MyEdgeProp,
no_property, propOrderedMultisetS> PropOrderedGraph;
}
using namespace boost;
int main() {
PropOrderedGraph g;
// ... adding some vertices and edges
for (auto e_range=edges(g); e_range.first != e_range.second; ++e_range.first) {
// works! prints the edges ordered by weight
std::cout << g[*e_range.first].weight << std::endl;
}
for (auto v_range=vertices(g); v_range.first != v_range.second; ++v_range.first) {
// works! prints all vertices (random order)
std::cout << g[*v_range.first].v << std::endl;
}
auto first_vertex = *vertices(g).first;
for (auto adj_v_range=adjacent_vertices(first_vertex, g); adj_v_range.first != adj_v_range.second; ++adj_v_range.first) {
// problem: dereferencing causes compiler error, see below
std::cout << g[*adj_v_range.first].v << std::endl;
}
return 0;
}
Dereferencing the iterator in the third for-loop causes a compiler error:
/usr/include/boost/graph/detail/adjacency_list.hpp:293:69: error: invalid initialization of reference of type ‘MyEdgeProp&’ from expression of type ‘const MyEdgeProp’
inline Property& get_property() { return m_iter->get_property(); }
Any ideas how I could fix that error or how else I could accomplish the task?
I changed the graph library and now am using LEMON, which provides a class IterableValueMap for my task.

Is there a way to find the C++ mangled name to use in GetProcAddress?

The common "solution" to use GetProcAddress with C++ is "extern "C", but that breaks overloading. Name mangling allows multiple functions to co-exist, as long as their signature differs. But is there a way to find these mangled names for GetProcAddress?
The VC++ compiler knows its own name mangling scheme, so why not use that? Inside template<typename T> T GetProcAddress(HMODULE h, const char* name), the macro __FUNCDNAME__ contains the mangled name of GetProcAddress. That includes the T part. So, inside GetProcAddress<void(*)(int), we have a substring with the mangled name of void(*)(int). From that, we can trivially derive the mangled name of void foo(int);
This code relies on the VC++ macro __FUNCDNAME__. For MinGW you'd need to base this on __PRETTY_FUNCTION__ instead.
FARPROC GetProcAddress_CppImpl(HMODULE h, const char* name, std::string const& Signature)
{
// The signature of T appears twice in the signature of T GetProcAddress<T>(HMODULE, const char*)
size_t len = Signature.find("##YA");
std::string templateParam = Signature.substr(0, len);
std::string returnType = Signature.substr(len+4);
returnType.resize(templateParam.size()); // Strip off our own arguments (HMODULE and const char*)
assert(templateParam == returnType);
// templateParam and returnType are _pointers_ to functions (P6), so adjust to function type (Y)
std::string funName = "?" + std::string(name) + "##Y" + templateParam.substr(2);
return ::GetProcAddress(h, funName.c_str());
}
template <typename T>
T GetProcAddress(HMODULE h, const char* name)
{
// Get our own signature. We use `const char* name` to keep it simple.
std::string Signature = __FUNCDNAME__ + 18; // Ignore prefix "??$GetProcAddress#"
return reinterpret_cast<T>(GetProcAddress_CppImpl(h, name, Signature));
}
// Showing the result
struct Dummy { };
__declspec(dllexport) void foo( const char* s)
{
std::cout << s;
}
__declspec(dllexport) void foo( int i, Dummy )
{
std::cout << "Overloaded foo(), got " << i << std::endl;
}
__declspec(dllexport) void foo( std::string const& s )
{
std::cout << "Overloaded foo(), got " << s << std::endl;
}
__declspec(dllexport) int foo( std::map<std::string, double> volatile& )
{
std::cout << "Overloaded foo(), complex type\n";
return 42;
}
int main()
{
HMODULE h = GetModuleHandleW(0);
foo("Hello, ");
auto pFoo1 = GetProcAddress<void (*)( const char*)>(h, "foo");
// This templated version of GetProcAddress is typesafe: You can't pass
// a float to pFoo1. That is a compile-time error.
pFoo1(" world\n");
auto pFoo2 = GetProcAddress<void (*)( int, Dummy )>(h, "foo");
pFoo2(42, Dummy()); // Again, typesafe.
auto pFoo3 = GetProcAddress<void (*)( std::string const& )>(h, "foo");
pFoo3("std::string overload\n");
auto pFoo4 = GetProcAddress<int (*)( std::map<std::string, double> volatile& )>(h, "foo");
// pFoo4 != NULL, this overload exists.
auto pFoo5 = GetProcAddress<void (*)( float )>(h, "foo");
// pFoo5==NULL - no such overload.
}
Use dumpbin /exports 'file.dll' to get the decorated / undecorated name of all the symbols.
It's impossible to do it just by using GetProcAddress. However, one way to do it would be to enumerate all the exported functions for that particular module, and do a pattern matching to find all the mangled names.
More specifically, refer to this answer here. The only change you will need to make would be to pass in TRUE for MappedAsImage parameter and the return value of GetModuleHandle for Base parameter to ImageDirectoryEntryToData function call.
void EnumerateExportedFunctions(HMODULE hModule, vector<string>& slListOfDllFunctions)
{
DWORD *dNameRVAs(0);
_IMAGE_EXPORT_DIRECTORY *ImageExportDirectory;
unsigned long cDirSize;
_LOADED_IMAGE LoadedImage;
string sName;
slListOfDllFunctions.clear();
ImageExportDirectory = (_IMAGE_EXPORT_DIRECTORY*)
ImageDirectoryEntryToData(hModule,
TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &cDirSize);
if (ImageExportDirectory != NULL)
{
dNameRVAs = (DWORD *)ImageRvaToVa(LoadedImage.FileHeader,
LoadedImage.MappedAddress,
ImageExportDirectory->AddressOfNames, NULL);
for(size_t i = 0; i < ImageExportDirectory->NumberOfNames; i++)
{
sName = (char *)ImageRvaToVa(LoadedImage.FileHeader,
LoadedImage.MappedAddress,
dNameRVAs[i], NULL);
slListOfDllFunctions.push_back(sName);
}
}
}
I can't quite fathom why you'd ever want/need a constexpr version of MSalters' solution, but here it is, complete with namespace mangling. Use as
using F = int(double*);
constexpr auto f = mangled::name<F>([]{ return "foo::bar::frobnicate"; });
constexpr const char* cstr = f.data();
where F is the function signature and foo::bar::frobnicate is the (possibly qualified) name of the function.
#include<string_view>
#include<array>
namespace mangled
{
namespace detail
{
template<typename F>
inline constexpr std::string_view suffix()
{
auto str = std::string_view(__FUNCDNAME__);
return str.substr(14, str.size() - 87);
}
template<typename L>
struct constexpr_string
{
constexpr constexpr_string(L) {}
static constexpr std::string_view data = L{}();
};
template<typename Name>
inline constexpr int qualifiers()
{
int i = -2, count = -1;
while(i != std::string_view::npos)
{
i = Name::data.find("::", i + 2);
count++;
}
return count;
}
template<typename Name>
inline constexpr auto split()
{
std::array<std::string_view, qualifiers<Name>() + 1> arr = {};
int prev = -2;
for(int i = arr.size() - 1; i > 0; i--)
{
int cur = Name::data.find("::", prev + 2);
arr[i] = Name::data.substr(prev + 2, cur - prev - 2);
prev = cur;
}
arr[0] = Name::data.substr(prev + 2);
return arr;
}
template<typename F, typename Name>
struct name_builder
{
static constexpr auto suf = detail::suffix<F>();
static constexpr auto toks = split<Name>();
static constexpr auto len = Name::data.size() + suf.size() - toks.size() + 6;
static constexpr auto str = [] {
std::array<char, len> arr = {};
arr[0] = '?';
int i = 1;
for(int t = 0; t < toks.size(); t++)
{
if(t > 0)
arr[i++] = '#';
for(auto c : toks[t])
arr[i++] = c;
}
arr[i++] = '#';
arr[i++] = '#';
arr[i++] = 'Y';
for(auto c : suf)
arr[i++] = c;
return arr;
}();
};
}
template<typename F, typename LambdaString>
inline constexpr std::string_view name(LambdaString)
{
using Cs = detail::constexpr_string<LambdaString>;
using N = detail::name_builder<F, Cs>;
return {N::str.data(), N::len};
}
}
GodBolt

Resources