I got that message
no matching function for call to 'main()::MySeqInFileEnumerator::MySeqInFileEnumerator(const char [10])'
when im doing my string matching job.I have to method override existing code.I have to open an input text, and make an abstract file from it, then i have to do an optimistic linsearch.
#include <iostream>
#include "linsearch.hpp"
#include "seqinfileenumerator.hpp"
using namespace std;
struct MyPair
{
int azon;
int osszeg;
friend ifstream& operator>>(ifstream& f, MyPair& df);
};
ifstream& operator>>(ifstream& f, MyPair& df)
{
f >> df.azon >> df.osszeg;
return f;
}`enter code here`
int main()
{
class MyLinSearch: public LinSearch <int, true>
{
bool Cond(const int& e) const
{
return e<=-100000;
}
};
class MySeqInFileEnumerator: public SeqInFileEnumerator <MyPair>
{
void Next()
{
MyPair dx;
f >> dx;
df.azon=dx.azon;
df.osszeg=dx.osszeg;
while(dx.azon==df.azon)
{
dx.osszeg+=df.osszeg;
f >> dx;
}
}
};
MyLinSearch pr;
MySeqInFileEnumerator t("input.txt");
pr.AddEnumerator(&t);
pr.Run();
if (pr.Found())
{
cout << "false " << endl;
}
else cout << "true" << endl;
return 0;
}
As the error message says, the class has no constructor taking a string; yet you try to use one with
MySeqInFileEnumerator t("input.txt");
Perhaps the base class has a suitable constructor? In that case, you'll need to forward the argument:
explicit MySeqInFileEnumerator(char const * name) :
SeqInFileEnumerator<MyPair>(name)
{}
You forgot to add a suitable constructor. Something like this:
class MySeqInFileEnumerator: public SeqInFileEnumerator<MyPair>
{
public:
MySeqInFileEnumerator(char const * p) : SeqInFileEnumerator<MyPair>(p) { }
// ...
};
(This is assuming your base class has a corresponding constructor. Modify to taste.
Related
In the class base, we need to write a function such that printing an object will print arguments of an object using oops concept.
#include <iostream>
using namespace std;
class base{
int num;
string s;
public:
base(int elem,string p){
cout<<elem<<" "<<p<<endl;
}
// todo:
};
int main() {
base obj(12,"shivam");
// cout<<obj<<endl;
}
Your current idea is not far from working, except you print the constructor arguments to std::cout as soon as an instance of base is created - not when the programmer using the class expresses such a wish. What you need to do is to save the arguments given when constructing a base. You'll then be able to print them on demand.
Example:
#include <iostream>
#include <string>
class base {
public:
base(int n, const std::string& str) : // save the arguments given using
num(n), s(str) // <- the member initializer list
{
// empty constructor body
}
// declare a friend function with special privileges to read private
// member variables and call private functions:
friend std::ostream& operator<<(std::ostream&, const base&);
private:
int num;
std::string s;
};
// define the free (friend) function with access to private base members:
std::ostream& operator<<(std::ostream& os, const base& b) {
// here you format the output as you'd like:
return os << '{' << b.num << ',' << b.s << '}';
}
int main() {
base obj(12,"shivam");
std::cout << obj << '\n';
}
Output:
{12,shivam}
Try this:
int IntS(int y)
{
return y;
}
class base{
public:
base(int enume, std::string str)
{
std::cout << IntS(enume) << '\n';
std::cout << str << '\n;
}
};
int main()
{
base mybase(IntS(5), "five");
return 0;
}
See also, std::map:
How can I print out C++ map values?
I have a class named Demo and in that class I have overloaded the Text() method for setting and getting it's private variable called text.
#ifndef DEMO_H
#define DEMO_H
#include <string>
#include <iostream>
using namespace std;
class Demo {
string text;
public:
Demo() {};
Demo(string newText) : text(newText) {};
void Text(string updatedText);
string Text();
};
#endif // !DEMO_H
void Demo::Text(string updatedText) {
text = updatedText;
}
string Demo::Text() {
return text;
}
Then in another class, I have used the method in following way-
#include "Demo.h"
int main()
{
Demo d;
d.Text("test");
cout << d.Text() << endl;
return 0;
}
This works fine. However, I want to set the parameter of the method with "=" operator. So rather than
d.Text("test");
I want to do
d.Text = "test";
Is it possible to achieve in C++ and if so then how. I was thinking of operator overloading but I couldn't achieve the goal. Can anyone please suggest.
The closest you can get in c++ to express property like getter / setter functions similar as in c# is to provide class member functions like these:
class Demo {
string text;
public:
void Text(const string& updatedText) { text = updatedText; }
const string& Text() const { return text; }
};
That idiom is used a lot in the c++ standard library like here.
I want to do
d.Text = "test";
What you can do is
class Demo {
public:
string& Text() { return text; }
};
and
d.Text() = "test";
but that totally defeats the concept of encapsulation of data.
The right way to proceed is overloading the assignment '=' operator and use as below.
class Demo {
string text;
public:
Demo() {};
Demo(string newText) : text(newText) {};
**void operator =(const string& val) { text = val; }**
void Text(string updatedText);
string Text();
};
int main()
{
Demo d;
//d.Text("test");
d = "hello world";
cout << d.Text() << endl;
return 0;
}
You could define your Text property as an object T. T could then overload some common property operations ( haven't figured out how a common getter call like Object o; o.set(d.Text); would be implemented yet ) :
#include <iostream>
using namespace std;
class T {
string _text;
public:
void operator =(const string& t) { _text = t; }
friend ostream& operator<<(ostream& os, const T& obj)
{
cout << obj._text;
return os;
}
};
class Demo {
public:
T Text;
};
int main()
{
Demo d;
d.Text = "test";
cout << d.Text << endl;
}
Consider this pseudo-snippet:
class SomeClass
{
public:
SomeClass()
{
if(true)
{
fooCall = [](auto a){ cout << a.sayHello(); };
}
else
{
fooCall = [](auto b){ cout << b.sayHello(); };
}
}
private:
template<typename T>
std::function<void(T)> fooCall;
};
What I want is a class member fooCall which stores a generic lambda, which in turn is assigned in the constructor.
The compiler complains that fooCall cannot be a templated data member.
Is there any simple solution on how i can store generic lambdas in a class?
There is no way you'll be able to choose between two generic lambdas at run-time, as you don't have a concrete signature to type-erase.
If you can make the decision at compile-time, you can templatize the class itself:
template <typename F>
class SomeClass
{
private:
F fooCall;
public:
SomeClass(F&& f) : fooCall{std::move(f)} { }
};
You can then create an helper function to deduce F:
auto makeSomeClassImpl(std::true_type)
{
auto l = [](auto a){ cout << a.sayHello(); };
return SomeClass<decltype(l)>{std::move(l)};
}
auto makeSomeClassImpl(std::false_type)
{
auto l = [](auto b){ cout << b.sayHello(); };
return SomeClass<decltype(l)>{std::move(l)};
}
template <bool B>
auto makeSomeClass()
{
return makeSomeClassImpl(std::bool_constant<B>{});
}
I was not able to store std::function<> as a generic lambda in the class directly as a member. What I was able to do was to specifically use one within the class's constructor. I'm not 100% sure if this is what the OP was trying to achieve but this is what I was able to compile, build & run with what I'm suspecting the OP was aiming for by the code they provided.
template<class>
class test {
public: // While testing I changed this to public access...
// Could not get object below to compile, build & run
/*template<class U = T>
static std::function<void(U)> fooCall;*/
public:
test();
};
template<class T>
test<T>::test() {
// This would not compile, build & run
// fooCall<T> = []( T t ) { std::cout << t.sayHello(); };
// Removed the variable within the class as a member and moved it here
// to local scope of the class's constructor
std::function<void(T)> fooCall = []( auto a ) { std::cout << a.sayHello(); };
T t; // created an instance of <Type T>
fooCall(t); // passed t into fooCall's constructor to invoke the call.
}
struct A {
std::string sayHello() { return "A say's Hello!\n"; }
};
struct B {
std::string sayHello() { return "B say's Hello!\n"; }
};
int main() {
// could not instantiate an object of SomeClass<T> with a member of
// a std::function<> type that is stored by a type of a generic lambda.
/*SomeClass<A> someA;
SomeClass<B> someB;
someA.foo();
someB.foo();*/
// Simply just used the object's constructors to invoke the locally stored lambda within the class's constructor.
test<A> a;
test<B> b;
std::cout << "\nPress any key & enter to quit." << std::endl;
char c;
std::cin >> c;
return 0;
}
With the appropriate headers the above as is should compile, build & run giving the output below (At least in MSVS 2017 on Windows 7 64bit did); I left comments where I ran into errors and tried multiple different techniques to achieve a working example, errors occurred as others suggested and I found even more while working with the above code. What I was able to compile, build and run came down to this simple bit of code here without the comments. I also added another simple class to show it will work with any type:
template<class>
class test {
public:
test();
};
template<class T>
test<T>::test() {
std::function<void( T )> fooCall = []( auto a ) { std::cout << a.sayHello(); };
T t;
fooCall( t );
}
struct A {
std::string sayHello() { return "A say's Hello!\n"; }
};
struct B {
std::string sayHello() { return "B say's Hello!\n"; }
};
struct C {
int sayHello() { return 100; }
};
int main() {
test<A> testA;
test<B> testB;
test<C> testC;
std::cout << "\nPress any key & enter to quit." << std::endl;
char c;
std::cin >> c;
return 0;
}
Output:
A say's Hello!
B say's Hello!
100
Press any key & enter to quit
I don't know if this will help the OP directly or indirectly or not but if it does or even if it doesn't it is still something that they may come back to and build off of.
you can simply use a template class or...
If you can get away with using c++17, you could make fooCall's type std::function<void(const std::any&)> and make a small wrapper for executing it.
method 1 : simply use a template class (C++14).
method 2 : seems to mimic the pseudo code exactly as the OP intended (C++17).
method 3 : is a bit simpler and easier to use than method 2 (C++17).
method 4 : allows us to change the value of fooCall (C++17).
required headers and test structures for the demo :
#include <any> //not required for method 1
#include <string>
#include <utility>
#include <iostream>
#include <functional>
struct typeA {
constexpr const char * sayHello() const { return "Hello from A\n"; }
};
struct typeB {
const std::string sayHello() const { return std::string(std::move("Hello from B\n")); }
};
method 1 :
template <typename T>
class C {
const std::function<void(const T&)> fooCall;
public:
C(): fooCall(std::move([](const T &a) { std::cout << a.sayHello(); })){}
void execFooCall(const T &arg) {
fooCall(arg);
}
};
int main (void) {
typeA A;
typeB B;
C<typeA> c1;
C<typeB> c2;
c1.execFooCall(A);
c2.execFooCall(B);
return 0;
}
method 2 :
bool is_true = true;
class C {
std::function<void(const std::any&)> fooCall;
public:
C() {
if (is_true)
fooCall = [](const std::any &a) { std::cout << std::any_cast<typeA>(a).sayHello(); };
else
fooCall = [](const std::any &a) { std::cout << std::any_cast<typeB>(a).sayHello(); };
}
template <typename T>
void execFooCall(const T &arg) {
fooCall(std::make_any<const T&>(arg));
}
};
int main (void) {
typeA A;
typeB B;
C c1;
is_true = false;
C c2;
c1.execFooCall(A);
c2.execFooCall(B);
return 0;
}
method 3 :
/*Note that this very closely resembles method 1. However, we're going to
build off of this method for method 4 using std::any*/
template <typename T>
class C {
const std::function<void(const std::any&)> fooCall;
public:
C() : fooCall(std::move([](const std::any &a) { std::cout << std::any_cast<T>(a).sayHello(); })) {}
void execFooCall(const T &arg) {
fooCall(std::make_any<const T&>(arg));
}
};
int main (void) {
typeA A;
typeB B;
C<typeA> c1;
C<typeB> c2;
c1.execFooCall(A);
c2.execFooCall(B);
return 0;
}
method 4 :
/*by setting fooCall outside of the constructor we can make C a regular class
instead of a templated one, this also complies with the rule of zero.
Now, we can change the value of fooCall whenever we want.
This will also allow us to do things like create a container that stores
a vector or map of functions that each take different parameter types*/
class C {
std::function<void(const std::any&)> fooCall; //could easily be replaced by a vector or map
public:
/*could easily adapt this to take a function as a parameter so we can change
the entire body of the function*/
template<typename T>
void setFooCall() {
fooCall = [](const std::any &a) { std::cout << std::any_cast<T>(a).sayHello(); };
}
template <typename T>
void execFooCall(const T &arg) {
fooCall(std::make_any<const T&>(arg));
}
};
int main (void) {
typeA A;
typeB B;
C c;
c.setFooCall<typeA>;
c.execFooCall(A);
c.setFooCall<typeB>;
c.execFooCall(B);
return 0;
}
Output from Any method
Hello from A
Hello from B
I need to do some equality checks with different types on a class hierarchy. In pseudo code:
#include <string>
#include <memory>
#include <iostream>
using namespace std;
class ComplexType {};
class Property {};
class IntegerProperty : public Property {
public:
int inner;
};
class StringProperty : public Property {
public:
string inner;
};
class ComplexTypeProperty : public Property {
ComplexType inner;
};
int main() {
shared_ptr<Property> p1 = getSomewhere(); //this is in fact a pointer on IntegerProperty
shared_ptr<Property> p2 = getSomewhere(); // this is in fact a pointer on StringProperty
shared_ptr<Property> p3 = getSomewhere(); // this is in fact a pointer on CompleyTypeProperty
ComplexType c;
cout << ((*p1) == 2);
cout << ((*p2) == "foo");
cout << ((*p3) == c);
}
It it simple to provide a operator== for the derived classes, but I cannot cast before checking, because the type of p1 and p2 is not clear at compile time.
Another way I know is to write the operator== function in the Property base class and throw some exceptions if the type is wrong, but I want, that the Property class can be subclassed later without changing the code for Property and it will work, too.
Templating Property is also not (directly) possible, because e.g. in my code a vector<shared_ptr<Property>> has to exist.
Is there some (generic) way to implement main() to get the equality checks, so that later subclassing of Property without changing the class itself is possible?
Have found some way of solving this. I'm not quite happy with the code. So if anyone has a better solution, please provide it.
#include <string>
#include <memory>
#include <iostream>
using namespace std;
class ComplexType {
public:
bool operator==(const ComplexType& i) {
return true;
}
};
inline ostream& operator<<(ostream& os, const ComplexType& c) {
os << "ComplexType";
return os;
}
class Property {
public:
virtual ~Property() {}
};
template <class T>
class LayerProperty : public Property {
private:
T inner;
public:
LayerProperty(T t) : inner(t) {}
bool operator==(const T i) {
return inner == i;
}
};
int main() {
shared_ptr<Property> p1 = make_shared<LayerProperty<int>>(LayerProperty<int>(5));
shared_ptr<Property> p2 = make_shared<LayerProperty<string>>(LayerProperty<string>("foo"));
shared_ptr<Property> p3 = make_shared<LayerProperty<ComplexType>>(LayerProperty<ComplexType>(ComplexType()));
ComplexType c;
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(2)>>(p1)) == 2) << "\n";
// special case std::string
auto a = "foo";
auto s = "";
if (typeid(a) == typeid(s)) {
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(string(a))>>(p2)) == a) << "\n";
}
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(c)>>(p3)) == c) << "\n";
return 0;
}
I wonder how to hide a real property field (not make it private or public but force to use setters and getters) and provide him with simple setter and getter. So I wonder how to create api like:
private:
Property( int my_a);
public:
Property( int my_b);
...
{
set_my_a(1);
cout << get_my_a() << endl;
// my_a = 13; // will cause compiler error
...
How to create such thing via Boost preprocessor?
Do you really need to use boost preprocessor?
you have a solution without boost below:
// property.h
#include <stdio.h>
#define property(type) struct : public Property <type>
template <typename T>
class Property
{
protected:
T value;
public:
virtual T get() {
return value;
}
virtual void set(T new_value) {
value = new_value;
}
};
usage example:
// test.cpp
#include "property.h"
class Test {
public:
property(int) {} a;
property(int) {
int get() {
return value * 10;
}
} b;
property(int) {
void set(int x) {
value = x * 200;
}
} c;
property(int) {
int get() {
return value * 3000;
}
void set(int x) {
value = x * 443;
}
} d;
};
main()
{
Test t;
printf("i\ta\tb\tc\td\t\n");
for (int i=0; i<10; i++) {
t.a.set(i);
t.b.set(i);
t.c.set(i);
t.d.set(i);
printf("%i\t%i\t%i\t%i\t%i\n", i, t.a.get(), t.b.get(), t.c.get(), t.d.get());
}
}
The wikipedia solution in http://en.wikipedia.org/wiki/Property_(programming)#C.2B.2B is good but needs a minimal modification to become useful, because without the protected statement you cant write your own getters and setters.
#include <iostream>
template <typename T>
class property {
protected:
T value;
public:
T & operator = (const T &i) {
::std::cout << i << ::std::endl;
return value = i;
}
operator T const & () const {
return value;
}
};
struct Bar {
property <bool> alpha;
struct :public property <int> {
int & operator = (const int &i) {
::std::cout << "new setter " << i << ::std::endl;
return value = i;
}
} bravo;
};
main()
{
Bar b;
b.alpha = false;
b.bravo = (unsigned int) 1;
}
You can change a little more if you want:
#include <iostream>
#define SETTER(type) public: type& operator=(const type new_value)
#define GETTER(type) public: operator type const & () const
template <typename T>
class Property {
protected:
T value;
public:
T & operator = (const T &i) {
::std::cout << i << ::std::endl;
return value = i;
}
template <typename T2> T2 & operator = (const T2 &i) {
::std::cout << "T2: " << i << ::std::endl;
T2 &guard = value;
throw guard; // Never reached.
}
operator T const & () const {
return value;
}
};
struct Bar {
Property <bool> alpha;
struct:Property <int> {
SETTER(int) {
value = new_value * 1000;
::std::cout << "new method " << new_value << ::std::endl;
return value;
}
GETTER(int) {
return value/1000;
}
} bravo;
};
main()
{
Bar b;
b.alpha = false;
b.bravo = (unsigned int) 1;
::std::cout << b.bravo << ::std::endl;
}
Rather than rewrite an example of the implementation, this is the link for one on Wikipedia: http://en.wikipedia.org/wiki/Property_(programming)#C.2B.2B
This basically forces the property to be accessed through getter/setter methods. The upgrade you would need to get your desired effect is the ability to pass functors to these properties. There are plenty of ideas on implementing these; the best approach I cannot advise and depends on your developmental needs. Personally, it feels like over engineering and prefer to just use Pimpl to hide my private details and just provide the getters/setters explicitly.