cpp no matching function call for call to constructor. Why? - c++

Below is my code:
// this code illustrates iterating through a nested hashmap.
#include <iostream>
#include "imported.hpp"
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
#define MAX_LINE_LENGTH 999
using namespace std;
class State
{
public:
vector<string> vec;
string state_string;
State(string state_string, vector<string> vec);
};
State::State(string state_string, vector<string> vec)
{
this->state_string = state_string;
this->vec = vec;
}
class Heuristic
{
public:
State goal_state;
string type;
Heuristic(string type, State goal_state);
};
Heuristic::Heuristic(string type, State goal_state)
{
this->type = type;
this->goal_state = goal_state;
}
int main(int argc, char const *argv[])
{
}
When I try to compile it using:
g++ filename.cpp
The following output is produced:
$ g++ main.cpp
main.cpp: In constructor ‘Heuristic::Heuristic(std::string, State)’:
main.cpp:36:51: error: no matching function for call to ‘State::State()’
Heuristic::Heuristic(string type, State goal_state)
^
main.cpp:21:1: note: candidate: State::State(std::string, std::vector<std::basic_string<char> >)
State::State(string state_string, vector<string> vec)
^~~~~
main.cpp:21:1: note: candidate expects 2 arguments, 0 provided
main.cpp:12:7: note: candidate: State::State(const State&)
class State
^~~~~
main.cpp:12:7: note: candidate expects 1 argument, 0 provided
main.cpp:12:7: note: candidate: State::State(State&&)
main.cpp:12:7: note: candidate expects 1 argument, 0 provided
I am confused as to why this is happening since I am not even calling the constructor but rather am defining a function's method signature into which the user should be able to pass an existent State object. Please assist.

The Heuristic constructor is built using assignment operators which involves the default construction of its member objects. Since State does not have a default constructor, this form of construction will fail.
There are two ways of solving this:
If the members have user-defined constructors, provide default-constructors also for them .
Use initializer lists for your constructor instead of assignments within the body of the constructor.
Of these two methods, the second one is more preferable. The reasons for this are outlined in the FAQ: Should my constructors use “initialization lists” or “assignment”?

Related

ambiguity of overloaded function taking constant Eigen argument

I've designed a class with two overloaded functions taking Eigen data structures of different sizes.
The code compiles as long as I'm passing lvalues but if I pass an rvalue I get a compiler error ambiguity because both return the same ConstantReturnType.
Here is a MWE:
#include <iostream>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
class MyOverloadAmbiguity {
public:
void ambiguousOverload(const Eigen::Vector3d& v) {
std::cout << "I'm taking a Vector3d\n";
}
void ambiguousOverload(const Eigen::Vector4d& v){
std::cout << "I'm taking a Vector4d\n";
}
};
int main()
{
MyOverloadAmbiguity moa;
Eigen::Vector3d v3;
moa.ambiguousOverload(v3); // <--- this works
moa.ambiguousOverload(Eigen::Vector4d::Zero()); // <--- this doesn't
return 0;
}
main.cpp:26: error: call of overloaded ‘ambiguousOverload(const ConstantReturnType)’ is ambiguous
26 | moa.ambiguousOverload(Eigen::Vector4d::Zero());
| ^
main.cpp:10:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector3d&)’
10 | void ambiguousOverload(const Eigen::Vector3d& v) {
| ^~~~~~~~~~~~~~~~~
main.cpp:13:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector4d&)’
13 | void ambiguousOverload(const Eigen::Vector4d& v){
| ^~~~~~~~~~~~~~~~~
Is there a way to avoid this without explicitly changing the function names or add extra arguments just to avoid the ambiguity?
Your example does not work because the return type of Zero() is not a matrix, but an Eigen expression.
Thus, one way of achieving what you want with minimal changes is to use explicit matrix evaluation:
moa.ambiguousOverload(Eigen::Vector4d::Zero().eval());
You may also want to consider writing functions taking Eigen expressions as parameters (rather than explicit matrices), as an alternative solution.

C++ Problems Pushing Initializer List onto a Standard Vector If the Struct Contains a Mutex

I'm currently working on a project in C++ in which I have a list of structs stored in a vector that have a lot processing associated with them. In order to speed things up, I've chosen to split the program across multiple threads, and the lazy way I've chosen to do this is by adding a mutex to each struct in the standard library vector. This way I can have a number of threads iterate over the array and basically take ownership of the individual elements by calling mutex.try_lock(), and either completing the associated processing with that element, or moving onto the next open one.
Before we get started, note that the following actually does work.
#include <mutex>
#include <vector>
struct foo {
int a;
std::mutex b;
};
void working_demo () {
// assign by initializer list
foo f = {.a = 1};
}
int main () {
working_demo();
}
So, I intend to populate my standard vector in a way very similar to above, and it doesn't work.
#include <mutex>
#include <vector>
struct foo {
int a;
std::mutex b;
};
void broken_demo () {
std::vector<foo> bar;
// assign by initializer list
bar.push_back({.a = 1});
}
int main () {
broken_demo();
}
Compiler Error:
clang++ -std=c++11 -Wall -Wextra -Wfatal-errors -pedantic -I./ -c -o demo.o demo.cpp
demo.cpp:13:20: warning: designated initializers are a C99 feature [-Wc99-extensions]
bar.push_back({.a = 1});
^~~~~~
In file included from demo.cpp:1:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/mutex:38:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/tuple:39:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/array:39:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/stdexcept:39:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/string:41:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/allocator.h:46:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/x86_64-pc-linux-gnu/bits/c++allocator.h:33:
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/ext/new_allocator.h:146:8: fatal error: call to implicitly-deleted copy constructor of 'foo'
_Up(std::forward<_Args>(__args)...)))
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/alloc_traits.h:483:24: note: in instantiation of exception specification for
'construct<foo, foo>' requested here
noexcept(noexcept(__a.construct(__p, std::forward<_Args>(__args)...)))
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/vector.tcc:115:21: note: in instantiation of exception specification for 'construct<foo, foo>'
requested here
_Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish,
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_vector.h:1201:9: note: in instantiation of function template specialization
'std::vector<foo, std::allocator<foo> >::emplace_back<foo>' requested here
{ emplace_back(std::move(__x)); }
^
demo.cpp:13:9: note: in instantiation of member function 'std::vector<foo, std::allocator<foo> >::push_back' requested here
bar.push_back({.a = 1});
^
demo.cpp:6:16: note: copy constructor of 'foo' is implicitly deleted because field 'b' has a deleted copy constructor
std::mutex b;
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/std_mutex.h:94:5: note: 'mutex' has been explicitly marked deleted here
mutex(const mutex&) = delete;
^
I'm fairly certain that this is saying the reason this won't work is that the structure is attempting to call the copy constructor for the mutex, which in fact does not have a copy constructor. I explicitly don't want to do be doing this.
My initial thought is that in order to make sure it doesn't even try to call the copy constructor for the mutex, I can create my own constructor for my class and basically explicitly leave out the copying for the mutex. This method would look like this - but it also doesn't work.
#include <mutex>
#include <vector>
struct foo {
foo (int A): a(A) {;}
int a;
std::mutex b;
};
void broken_demo () {
std::vector<foo> bar;
// assign by initializer list
bar.emplace_back(1);
}
int main () {
broken_demo();
}
Compiler Error:
clang++ -std=c++11 -Wall -Wextra -Wfatal-errors -pedantic -I./ -c -o demo.o demo.cpp
In file included from demo.cpp:2:
In file included from /usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/vector:65:
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_construct.h:75:38: fatal error: call to implicitly-deleted copy constructor of 'foo'
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_uninitialized.h:83:8: note: in instantiation of function template specialization
'std::_Construct<foo, foo>' requested here
std::_Construct(std::__addressof(*__cur), *__first);
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_uninitialized.h:134:2: note: in instantiation of function template specialization
'std::__uninitialized_copy<false>::__uninit_copy<std::move_iterator<foo *>, foo *>' requested here
__uninit_copy(__first, __last, __result);
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_uninitialized.h:289:19: note: in instantiation of function template specialization
'std::uninitialized_copy<std::move_iterator<foo *>, foo *>' requested here
{ return std::uninitialized_copy(__first, __last, __result); }
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/stl_uninitialized.h:310:19: note: in instantiation of function template specialization
'std::__uninitialized_copy_a<std::move_iterator<foo *>, foo *, foo>' requested here
return std::__uninitialized_copy_a
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/vector.tcc:473:10: note: in instantiation of function template specialization
'std::__uninitialized_move_if_noexcept_a<foo *, foo *, std::allocator<foo> >' requested here
= std::__uninitialized_move_if_noexcept_a
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/vector.tcc:121:4: note: in instantiation of function template specialization 'std::vector<foo,
std::allocator<foo> >::_M_realloc_insert<int>' requested here
_M_realloc_insert(end(), std::forward<_Args>(__args)...);
^
demo.cpp:15:9: note: in instantiation of function template specialization 'std::vector<foo, std::allocator<foo> >::emplace_back<int>' requested here
bar.emplace_back(1);
^
demo.cpp:8:16: note: copy constructor of 'foo' is implicitly deleted because field 'b' has a deleted copy constructor
std::mutex b;
^
/usr/sup/bin/../lib/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/bits/std_mutex.h:94:5: note: 'mutex' has been explicitly marked deleted here
mutex(const mutex&) = delete;
^
1 error generated.
Any thoughts on a solution to this? I'm hoping to keep the code relatively simple, but I'm uncertain how to make the standard vector behave, or at least use it properly.
The problem is that in your code instances of foo are passed by value. So when you put something into the vector, a copy needs to be created. A simple way to avoid that would be to put pointers to foo into the vector. You can wrap the pointers into some reference-counting mechanism so that you don't have to keep track of freeing the objects.
Here is a short example using std::unique_ptr that will auto-delete all foo instances in the vector when the vector goes out of scope:
#include <mutex>
#include <vector>
#include <memory>
#include <iostream>
#include <functional>
struct foo {
foo(int A) : a(A) {}
int a;
std::mutex b;
};
void fixed_demo () {
std::vector<std::unique_ptr<foo>> bar;
std::unique_ptr<foo> p(new foo(1));
bar.push_back(std::move(p));
bar.emplace_back(new foo(2));
for (auto it = bar.begin(); it != bar.end(); ++it) {
(*it)->b.lock();
std::cout << (*it)->a << std::endl;
(*it)->b.unlock();
}
}
int main () {
fixed_demo();
return 0;
}
After looking at one of the solutions, I think actually this solution fits best what I was going for. I wouldn't have been able to figure this out without the helpful advice above.
#include <mutex>
#include <vector>
struct foo {
int a;
std::mutex b;
foo (int a) : a(a) {;}
foo (const foo &f) : a(f.a) {;}
};
void other_fixed_demo ()
{
std::vector<foo> bar;
bar.emplace_back(1);
}
int main () {
other_fixed_demo();
}
I couldn't say why, but apparently two things are happening here. First, we are calling the constructor with the 1 input, and then somewhere within emplace_back() we're calling the copy constructor. Both need to explicitly not include the mutex in each way of creating the struct, and the above solution avoids that.

No matching function for call to constructor class

I'm trying to make the constructor for a subclass. But I keep getting this error message. I've tried searching here, but none of the answers I found applied to my problem. Sorry if it's been asked before.
In constructor 'EixoDinamico::EixoDinamico(double, double, Serie*, bool)':
error: no matching function for call to 'Eixo::Eixo()'
note: candidates are:
note: Eixo::Eixo(std::string, double, double)
note: candidate expects 3 arguments, 0 provided
note: Eixo::Eixo(const Eixo&)
note: candidate expects 1 argument, 0 provided
EDIT: If I rewrite the code so that the subclass is now a class on its own, the problem disappears, but I need it to be a subclass.
Here are the codes:
Eixo.h
#ifndef EIXO_H
#define EIXO_H
#include <iostream>
using namespace std;
class Eixo
{
public:
Eixo(string titulo, double minimo, double maximo);
virtual ~Eixo();
private:
string titulo;
double minimo;
double maximo;
};
#endif // EIXO_H'
Eixo.cpp
#include "Eixo.h"
#include <iostream>
Eixo::Eixo(string titulo, double minimo, double maximo)
{
this->maximo = maximo;
this->minimo = minimo;
this->titulo = titulo;
}
Eixo::~Eixo()
{
//dtor
}
EixoDinamico.h
#ifndef EIXODINAMICO_H
#define EIXODINAMICO_H
#include "Eixo.h"
class EixoDinamico : public Eixo
{
public:
EixoDinamico(double minimoPadrao, double maximoPadrao, Serie*
base, bool orientacaoHorizontal);
virtual ~EixoDinamico();
private:
};
#endif // EIXODINAMICO_H
EixoDinamico.cpp
#include "EixoDinamico.h"
#include "Eixo.h"
EixoDinamico::EixoDinamico(double minimoPadrao, double maximoPadrao, Serie*
base, bool orientacaoHorizontal):Eixo()
{
if(base->getQuantidade()<2){
inicioEixo = minimoPadrao;
fimEixo = maximoPadrao;
}
limiteInferior = base->getLimiteInferior();
limiteSuperior = base->getLimiteSuperior();
if (orientacaoHorizontal){
inicioEixo = limiteInferior->getX();
fimEixo = limiteSuperior->getX();
}
else{
inicioEixo = limiteInferior->getY();
fimEixo = limiteSuperior->getY();
}
}
EixoDinamico::~EixoDinamico()
{
//dtor
}
In the constructor of EixoDinamico you're calling the default constructor of Eixo (Eixo()), but that doesn't exist. The declaration of a custom construct for Eixo disables the automatic generation of a default constructor and you haven't declared one explicitly. To do that, add
Eixo() = default;
to the declaration of Eixo or implement one yourself.
Also make sure that calling the default constructor is really what you want. As underscore_d has pointed out, that doesn't make much sense.

No matching function call call to constructor in header file

I have seen similar questions asked and tried their solutions but the answers to them do not seem to work. I have the following code:
.h
#include <iostream>
#include <vector>
#include <string>
using std::string; using std::vector;
struct DialogueNode;
struct DialogueOption {
string text;
DialogueNode *next_node;
int return_code;
DialogueOption(string t, int rc, DialogueNode * nn) : text{t},
return_code{rc}, next_node{nn} {}
};
struct DialogueNode {
string text;
vector <DialogueOption> dialogue_options;
DialogueNode();
DialogueNode(const string &);
};
struct DialogueTree {
DialogueTree() {}
void init();
void destroyTree();
int performDialogue();
private:
vector <DialogueNode*> dialogue_nodes;
};
.cpp
#include "dialogue_tree.h"
DialogueNode::DialogueNode(const string &t) : text{t} {}
void DialogueTree::init() {
string s = "Hello";
for(int i = 0; i < 5; i++) {
DialogueNode *node = new DialogueNode(s);
dialogue_nodes.push_back(node);
delete node;
}
}
void DialogueTree::destroyTree() {
}
int DialogueTree::performDialogue() {
return 0;
}
int main() {
return 0;
}
I get the error: error: no matching function for call to ‘DialogueNode:: DialogueNode(std::__cxx11::string&)’ DialogueNode *node = new DialogueNode(s);
EDIT additional notes on error
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode()
dialogue_tree.h:17:8: note: candidate expects 0 arguments, 1 provided
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(const DialogueNode&)
dialogue_tree.h:17:8: note: no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const DialogueNode&’
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(DialogueNode&&)
dialogue_tree.h:17:8: note: no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘DialogueNode&&’
Which makes no sense to me because I have the constructor defined to take a string as an argument.
You've declared your constructor as:
DialogueNode(const string);
But defined it as:
DialogueNode(const string &t);
Those two aren't the same; the former takes a const string while the latter takes a const string reference. You'll have to add the & to specify a reference argument:
DialogueNode(const string &);
it is because in the constructor you are specifying that the parameter will be a string of constant type and when creating an object you are passing a string. The type mismatch is the problem, either fix the constructor parameter to string or change when you are creating an object.

skipping adding constructors when inheriting from std::string class

Tried to argument the std::string so that it supports method "bool operator==(int)". I got errors:
$ g++ -std=c++11 te2.cc
te2.cc: In function ‘int main(int, char**)’:
te2.cc:20:20: error: no matching function for call to ‘mstring::mstring(const char [4])’
te2.cc:20:20: note: candidates are:
te2.cc:10:7: note: mstring::mstring()
te2.cc:10:7: note: candidate expects 0 arguments, 1 provided
te2.cc:10:7: note: mstring::mstring(const mstring&)
te2.cc:10:7: note: no known conversion for argument 1 from ‘const char [4]’ to ‘const mstring&’
te2.cc:10:7: note: mstring::mstring(mstring&&)
te2.cc:10:7: note: no known conversion for argument 1 from ‘const char [4]’ to ‘mstring&&’
Here is the simple source:
#include <unordered_map>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class mstring : public string {
public:
//mstring (char* p) : std::string(p) {};
bool operator == (int x) {
int n = atoi(this->c_str());
return (n == x);
}
};
int main(int argc, char *argv[])
{
mstring t("123");
if (t == atoi(argv[1])) {
printf("yes\n");
} else {
printf("no\n");
}
}
If I uncomment the constructor /mstring (char* p) : std::string(p) {};, then it compiles and runs fine.
The question is, if it possible to make it work without defining the constructors for mstring, just use the whatever the constructors of the base class (there is no new data member anyway)? Thanks.
What about providing a free standing operator function instead of inheriting from std::string (which makes that code more usable overall):
bool operator==(const std::string& s, int i) {
int n = atoi(s.c_str());
return (n == i);
}
bool operator==(int i, const std::string& s) {
return s == i;
}
Or even more generic:
template<typename T>
bool operator==(const std::string& s, T t) {
std::istringstream iss;
iss << t;
return (s == iss.str());
}
Classes from the std namespace aren't intended to be inherited, but just used in interfaces and function parameters. Inheriting from those classes makes your code less usable, since clients need to use your implementation instead of just using the std type.
Also note: For your particular use case it's not necessary to convert anything at all, unless you want to assert that argv[1] contains a number (where atoi() certainly isn't the best method to do so, look up stoi() instead). You can just compare the strings:
if (std::string("123") == argv[1]) {
printf("yes\n");
} else {
printf("no\n");
}
you can explicitly inherit the constructors by adding
using string::string;
in your class