This question already has answers here:
default parameters in .h and .cpp files [duplicate]
(4 answers)
Closed 4 years ago.
Why are my default/optional parameters being ignored?
grid_model.h
class GridModel {
public:
GridModel();
void PrintGrid(bool);
};
grid_model.cpp
void GridModel::PrintGrid(bool flag = false) {
// things...
}
grid_model_test.cpp
ns::GridModel* gm = new GridModel();
gm->PrintGrid(true); // works
gm->PrintGrid(); // doesn't work
error:
grid_model_test.cpp:22:12: error: no matching function for call to ‘ns::GridModel::PrintGrid()’
gm->PrintGrid();
^
In file included from grid_model_test.cpp:2:0:
grid_model.h:27:7: note: candidate: void ns::GridModel::PrintGrid(bool)
void PrintGrid(bool);
^~~~~~~~~
When I use them elsewhere, they seem to work fine.
#include <iostream>
class Thing {
public:
void Whatever(bool);
};
void Thing::Whatever(bool flag = false) {
std::cout << "Parameter was: " << flag << std::endl;
}
int main() {
Thing* thing = new Thing();
thing->Whatever();
return 0;
}
Default parameter values should, as a good design practice, be placed in the declaration, not in the implementation:
class GridModel {
public:
GridModel();
void PrintGrid(bool flag=false);
};
void GridModel::PrintGrid(bool flag) {
// things...
}
Technically (as described in more length here http://en.cppreference.com/w/cpp/language/default_arguments ): the default arguments must be visible in the translation unit where the call is made. If you split the class in a grid_model.h and grid_model.cpp, any other .cpp (such as grid_model_test.cpp) that includes grid_model.h will not be aware of information that is only present in grid_model.cpp.
Related
This question already has answers here:
Using generic std::function objects with member functions in one class
(6 answers)
Closed 1 year ago.
I have an input class that has a method that is supposed to take function as an argument.
#include "pixelGameEngine.h"
#include <functional>
class Input
{
public:
Input() = default;
Input(const Input&) = delete;
Input& operator=(const Input&) = delete;
public:
static void OnDPress(olc::PixelGameEngine* pge, std::function<void()> DoIteration) noexcept
{
if (pge->GetKey(olc::D).bPressed)
{
DoIteration();
}
}
};
And I have a triangle processor class that is supposed to call that function.
#include "pixelGameEngine.h"
#include "input.h"
#include <functional>
class TriangleProcessor
{
//...
void DoIteration() noexcept{};
Input input;
void Run(olc::PixelGameEngine* pge)
{
Input::OnDPress(pge, DoIteration);
}
}
But I am getting an error "no suitable constructor exists to convert from "void () to "std::function<void ()>"on line Input::OnDPress(pge, DoIteration); with a red squiggly under DoIteration.
DoIteration is not a function. It's a method defined on the TriangleProcessor class. The usual std::function constructor you're trying to invoke is for producing std::function instances from callable objects or function pointers. DoIteration has an implied this argument.
Now, you're running this inside of Run, which as it happens has access to that implied this argument. So, in your case, we likely want to pass on the current this value. We can do that
Input::OnDPress(pge, [this]() { this->DoIteration(); });
This question already has an answer here:
Why class data members can't be initialized by direct initialization syntax?
(1 answer)
Closed 2 years ago.
In C++ I am having trouble passing parameters to the constructor for a template class.
it works when I instantiate from a function; but if I instantiate from a class, it gives "error C2059: syntax error: 'string'"
this is my very trimmed down example (names have been changed to protect the incent).
I am currently have std:latest enabled in Visual Studio 2019 and I've tried in 2017 as well.
#include <string>
#include <iostream>
template <class T>
class cap
{
public:
cap() : p(new(T)) {}
cap(const std::string& sfile, const std::string& sfunc, int line)
: m_file(sfile), m_func(sfunc), m_line(line) {}
~cap() {
delete p;
std::cout << "object freed: created in " << m_func << " line " << m_line << " of " << m_file;
}
private:
T* p{nullptr};
std::string m_file;
std::string m_func;
int m_line{0};
};
void foo()
{
cap<int> foo1("file", "func", 5); //<< compiles okay
}
class bar
{
cap<int> foo1("file", "func", 5); //<< "syntax error: 'string'"
};
IntelliSense says "expected a type specifier" when I hover the params used inside the class
My end goal is to have a macro to instantiate the object; passing in the location in source.The object thus knows where it was created.
#define CAP(type,var) cap<type> var(__FILE__, __func__, __LINE__)
CAP(somestruct, myvar);
// expands to:
cap<somestruct> myvar("file.cpp", "myfunc", 50);
For in-class initialization use the uniform initialization:
class bar
{
cap<int> foo1{"file", "func", 5};
};
#Alan has already provided a reference for why direct initialization using () don't work. It's also known as the C++ most vexed parse.
I'm a beginner with C++
I'm having a trouble when I set the header class values.
CalucateNumbers::CalucateNumbers() {
ResetValues();
}
void CalucateNumbers::ResetValues() {
firstNumber = 0;
secondNumber = 8;
}
CalucateNumber is missing exception specification noexcept
Help please?
This is the C plus plus Code file with the name FBullCowGame.cpp
#include "FBullCowGame.hpp"
FBullCowGame::FBullCowGame() {
Reset();
}
void FBullCowGame::Reset() {
CurrentTries = 0;
MaxTries = 8;
}
This is the header file with the name FBullCowGame.hpp
#ifndef FBullCowGame_hpp
#define FBullCowGame_hpp
#include <stdio.h>
#include <string>
#endif /* FBullCowGame_hpp */
class FBullCowGame {
public:
void Reset(); // TODO Make a reset void
// Not important.., The important is this ^^
private:
int CurrentTries;
int MaxTries;
};
Here is the MCVE on godbolt.
You were incorrect when you said "Yes it does" when asked whether the definition matches the header. It does not match the header, because it's not even present in the header!
Your class FBullCowGame doesn't declare a custom constructor, so the compiler created a default one. You then try to create a custom one, and the compiler thinks you're trying to implement the default constructor (which happens to be noexcept), so it says "This redeclaration doesn't match the implicit declaration."
Your real problem is that you forgot to tell the compiler "I'm going to give this class a custom constructor."
class FBullCowGame {
public:
FBullCowGame(); // <----- you forgot this
void Reset(); // TODO Make a reset void
// Not important.., The important is this ^^
private:
int CurrentTries;
int MaxTries;
};
(You also have a problem with the scope of the #ifdef guard in your header file.)
That's a very misleading error message. The problem is that the class definition does not declare a default constructor, but the source code attempts to implement one. To fix this, add a declaration for the default constructor to the class definition.
I am trying to implement an execution pattern which takes any function and executes it with its own conditions/preparations. Regardless of this being a useful thing to do, it just doesn't work. It seems i can't access the template overload of the "Execute"-function (called in "main").
Specifically: Why can't i call the overloaded template function of Execute?
This is the full program:
#include "stdafx.h"
#include <functional>
class TransparentFunctionWrapper
{
public:
virtual void Execute(std::function<void()> executeFunction) = 0;
template<class C>
C Execute(std::function<C(void)> executeFunction) // template-overload of the abstract function which will implicitly call it
{
C ret;
Execute( // calls the abstract function with a lambda function as parameter
[ret, executeFunction](void) -> C // lambda declaraction
{ //
ret = executeFunction; // lambda body
}); //
return ret;
}
};
class ExampleExecutor : public TransparentFunctionWrapper
{
public:
virtual void Execute(std::function<void()> executeFunction)
{
printf("executed before.");
executeFunction();
printf("executed after.");
}
};
void DoStuff() {}
int ReturnStuff() { return -5; }
int main()
{
ExampleExecutor executor;
executor.Execute(DoStuff);
int i = executor.Execute<int>(ReturnStuff); // Why does this not work? ERROR: "type name is not allowed"
getchar();
return 0;
}
Note: Visual Studio marks
Execute<int>(ReturnStuff) // "int" is marked as Error: type name is not allowed
The compilation puts out the error
"type 'int' unexpected"
Thanks to everyone willing to help!
ExampleExecutor::Execute is not overriding TransparentFunctionWrapper::Execute, and it is hiding it in the executor.Execute<int> call.
You must explicitly call TransparentFunctionWrapper::Execute, as it is hidden by ExampleExecutor::Execute. Here's a possible way of doing that:
int i = executor.TransparentFunctionWrapper::Execute<int>(ReturnStuff);
live example on coliru
This question already has an answer here:
g++ error: ‘vec’ does not name a type [duplicate]
(1 answer)
Closed 8 years ago.
Ok so I am trying to map some of my member functions in the .h file this is to be able to use the map when I implement the code. However, after hours I have gotten nowhere so I would like suggestions or if anyone knows how to implement this. For reference these are the errors.
./Assembler.h:51:2: error: C++ requires a type specifier for all declarations
functions["load"] = load;
^~~~~~~~~
./Assembler.h:51:12: error: size of array has non-integer type 'const char [5]'
functions["load"] = load;
^~~~~~
./Assembler.h:51:2: error: duplicate member 'functions'
functions["load"] = load;
^
As for my header file it with the problem coming from the map:
#include <vector>
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;
class Assembler {
public:
Assembler(string filename);//Argument will be passed from the os.cpp file
void parse();// Will go through the a file to output the .o file
void load();
void loadi();
void store();
void add();
void addi();
void addc();
void addci();
void sub();
void subi();
void subc();
void subci();
void ander();
void andi();
void xorer();
void xori();
void negate();
void shl();
void shla();
void shr();
void shra();
void compr();
void compri();
void getstat();
void putstat();
void jump();
void jumpl();
void jumpe();
void jumpg();
void call();
void ret();
void read();
void write();
void halt();
void noop();
private:
typedef void (*function)();
map<string, function> functions;
functions["load"] = load;
fstream in, out; //One will be the .s file while the other will be the .o file
string opcode;
int rd, rs, constant, addr, machcode; //Different parts of the instruction
};
Any help or suggestions would be appreciated. Thanks
Only static const integral data members can be initialized within a class. You probably need to move functions["load"] = load; to a function's definition.
And also, you need to change them to:
typedef void (Assembler::*function)();
...
functions["load"] = &Assembler::load;
Within C++ class declaration, you cannot have member initialiser or executable statement, Have this one
functions["load"] = load;
within constructor
Take a look at your class declaration: everything's compiling fine except
functions["load"] = load;
This is an assignment and initializes the functions map with something. That is not allowed in the declaration which is a "contract" (in the case of an interface) or "explanation" of how your class is composed and what methods/members has.
The right spot to put such an initialization is in your constructor's definition (i.e. in the part of the code that actually contains the code of your methods, specifically when the object gets created if you intend to initialize stuff.. i.e. the constructor).