How to pass enum in a scope to another as function argument? As this is failing:
enum class L;
struct TestClass
{
void foo(L n)
{
int v = static_cast<int>(n);
int r[v] = { 9 };
cout << "\n" << v << "\n";
}
};
int main()
{
enum class L : int
{
A, B, C, D
};
TestClass main;
main.foo(L::D);
return 0;
}
error: cannot convert ‘main()::L’ to ‘L’
80 | main.foo(L::D);
| ~~~^
| |
| main()::L
How to solve this (in exact place, not move enum to a scope else) ?
How to solve this (in the exact place, not move enum to a scope else)?
Cast the enum while passing as a parameter.
main.foo(static_cast<int>(L::D));
Then your member function would be
void foo(int n)
{
std::vector<int> r(n, 9); // used `std::vector` instead of VLA
std::cout << "\n" << n << "\n";
}
(See sample code)
Note that the VLAs are not part of standard C++. Read more in the following post:
Why aren't variable-length arrays part of the C++ standard?
Prefer using std::vector as shown in the above code sample.
In a nutshell, the problem is that you have an enum that you want to use in two places. To me, the most natural solution to this is to put the enum in its own header file and use it where it is required.
// my_enum.h
#pragma once
enum class L : int {
A, B, C, D
};
// TestClass.h
#pragma once
// Can forward declare L so long as we define the functions in the same cpp
// If original enum is in a namespace it needs to be forward declared in the same namespace
enum class L;
struct TestClass {
void foo(L n);
};
// TestClass.cpp
#include "TestClass.h"
#include "my_enum.h"
void TestClass::foo(L n)
{
// do stuff with n
}
// main.cpp
#include "TestClass.h"
#include "my_enum.h"
int main(){
TestClass main;
main.foo(L::D);
return 0;
}
How to solve this (in exact place, not move enum to a scope else) ?
I'm conscious that I've answered the question in a way you did not want, but I do not see why you wouldn't want to put the enum in its own file. Avoiding this will lead to problems at some point. The consequence of JeJo's solution is that you could pass any old integer in to foo() - it is essentially decoupled from the enum. If the integer value is supposed to originate from the enum L: 1) it isn't obvious from the function signature and 2) it is prone to misuse i.e. someone passing in a value they shouldn't.
If putting the enum in its own header file is an unacceptable solution, I'd be interested to know why.
Related
I want to create a class that contains a struct with a template. But it gives this error, and though I've seen other similar questions, I don't understand how or if I can declare this in a way that does not give this error. thanks for your help.
# include <iostream>
using namespace std;
template <class T>
class MyTmpl {
public:
MyTmpl() {}
T body;
};
struct s1_t {
std::string s;
int x;
};
MyTmpl<s1_t> myc();
myc.body.s = "s1";
myc.body.x = 7;
int main(int argc, char** argv) {
//std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}
This gives:
x.cpp:24:1: error: 'myc' does not name a type
myc.body.s = "s1";
^
myc.body.s = "s1";
myc.body.x = 7;
Your immediate error is because you have this code where no code should be (at file level, outside of any function). You need to move it into main (or somewhere else that is is allowed to be, but probably main in this case).
The reason you see the does not name a type is simply because code is unexpected at that point so the compiler thinks you're trying to declare something (like, for example, int x;).
You'll get the same error with the code snippet:
//using nontype = int;
nontype x;
because nontype is not actually a type. If you however uncomment the using (a slightly more modern typedef), the nontype becomes a type and the error disappears.
Your second problem is that MyTmpl<s1_t> myc(); is a function declaration, something that would become evident if you included in your main:
auto x = myc();
The linker would then complain about the lack of a myc function definition. You should change it to:
MyTmpl<s1_t> myc; // without the ().
Your third problem is that, while you're using the C++ language, you're not quite yet using the C++ mindset. The whole point of classes is to encapsulate behaviour and state, something that's rather nullified if everything in your class is public :-)
Eventually (with experience), you'll get into the habit of privatising as much as possible, providing constructors, getters, setters, and so forth. Not an immediate issue for you but certainly something you'll want to work toward.
With those changes (other the the "C++ification") and uncommenting your output statement, the following resulting code compiles and runs fine, producing s1:7 as expected:
#include <iostream>
template <class T> class MyTmpl {
public:
MyTmpl() { }
T body;
};
struct s1_t {
std::string s;
int x;
};
MyTmpl<s1_t> myc; // variable, rather than function.
// code not allowed here.
int main() {
myc.body.s = "s1"; // code allowed here.
myc.body.x = 7;
std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}
I'm trying to run some test code to learn c++, but I am getting an error telling me the reverseDigits function was not declared in the main.cpp scope:
error: 'reverseDigits' was not declared in this scope.
But the #include "Solutions.h" header was included in main.cpp, so I thought that it would be in scope.
I have checkout other questions, but the answers all relate to problems with circular header file inclusion, which I don't think is the problem here.
Do you know why I am seeing that error?
Solution.h
#ifndef SOLUTION_H
#define SOLUTION_H
class Solution {
public:
Solution();
~Solution();
int reverseDigits(int x);
};
#endif // SOLUTION_H
Solution.cpp
#include "Solution.h"
#include <string>
Solution::Solution()
{
}
Solution::~Solution()
{
}
int Solution::reverseDigits(int x) {
std::string num_string = std::to_string(x);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i > 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
main.cpp
#include <iostream>
#include "Solution.h"
int main()
{
int x {123};
int result = reverseDigits(x);
std::cout << result << std::endl;
return 0;
}
You declared reverseDigits as a member function of the Solution class, then defined it without qualifying it as a member of Solution (Edit: You've since changed it to match declaration and definition, but at point of use, you're trying to use an unqualified function, not a member of a Solution object). The declaration in the .h file is visible, but the definition in the .cpp is unrelated, and not visible to main.cpp.
Declare the function outside the class (since it's clearly unrelated to the class), and it should work, changing to:
class Solution {
public:
Solution();
~Solution();
};
int reverseDigits(int x); // NOT inside the class definition
I'll note: I have no idea why you have a Solution class at all. Defining reverseDigits doesn't require it, so I'm not seeing the point. If this is part of some automated evaluation framework, you'll have to give more details
Along with ShadowRanger's valid suggestion, I'll highlight upon how you could have used the data as part of your Solution class and applied the function on it.
Refactoring your class to
class Solution {
public:
Solution(int data);
~Solution();
int reverseDigits();
private:
int m_data;
};
Solution::Solution(int data)
{
m_data = data;
}
Solution::~Solution()
{
}
Even though you could have used std::reverse, fixing the error on the i>=0 is needed to have your own reverse function
int Solution::reverseDigits() {
std::string num_string = std::to_string(m_data);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i >= 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
Now call it from your main() as
int main() {
int x = 123;
Solution sol(x);
std::cout << sol.reverseDigits() << std::endl;
return 0;
}
I have two simple testing lines:
cout<<(cout<<"ok"<<endl, 8)<<endl;
cout<<(int i(8), 8)<<endl;
The first line worked, but the second failed compilation with
error: expected primary-expression before 'int'
For some reason, I do need a declaration in the comma operator. To be more specific, I want to declare some variables, obtain their values, and assign them to my constant class members from the initialization list of my class constructor. Following shows my intentions. If not achievable using comma operator, any another suggestions?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
void readFile(const string & fileName, int & a, int & b)
{
fstream fin(fileName.c_str());
if (!fin.good()) {cerr<<"file not found!"<<endl; exit(1);}
string line;
getline(fin, line);
stringstream ss(line);
try {ss>>a>>b;}
catch (...) {cerr<<"the first two entries in file "<<fileName<<" have to be numbers!"<<endl; exit(1);}
fin.close();
}
class A
{
private:
const int _a;
const int _b;
public:
A(const string & fileName)
:
_a((int a, int b, readFile(fileName,a,b), a)),
_b((int a, int b, readFile(fileName,a,b), b))
{
/*
int a, b;
readFile(fileName,a,b);
_a = a;_b = b;
*/
}
void show(){cout<<_a<<" "<<_b<<endl;}
};
int main()
{
A a("a.txt");
a.show();
}
Declarations are statements and not expressions. You cannot place statements inside of expressions, though you can place expressions inside of statements. Accordingly, you cannot declare a variable in the way that you're describing above. You'll need to separate it out into multiple different statements.
I would be surprised if if you actually needed to do this. If you do, there is probably something problematic about your design.
Hope this helps!
You should have a look at Boost Phoenix (which has phoenix::let to do roughly this). Bear in mind, Phoenix is an eDSL, really (embedded domain specific language).
You could do an ugly trick and abuse lambdas:
cout<< ([]->int{ int i(8); return 8; })() <<endl;
A lambda allows a declaration within an expression. So this is possible:
std::cout << ([]{ int i(8); m_i = i; }(), 8) << std::endl;
But it's really weird - I assume this will be in some #define macro that makes it appear closer to normal.
You cannot. This is unpossible in C++. The fact that you are trying to do this is also a code smell. Something's not right here.
I want to declare some variables, obtain their values, and assign them
to my constant class members from the initialization list of my class
constructor. Not sure how to achieve this.
You didn't say what you intended to do with these variables you declare after you've used the values, but I'm guessing that once you've finished with the values, you've finished with the variables. In other words, they are temporary.
Your edited example suggests that my assumption is correct. It also confirms the code smell. Based on your (intended) code, you are going to read the file twice.
I'd say the most straightforward way to do this is to use an intermediary, kind of like a factory class. This also has the benefit of being able to read the file only once, as opposed to twice as you are doing now.
void readFile (const std::string& fileName, int& a, int& b)
{
// some magic
a = 42;
b = 314;
}
class FileReader
{
public:
FileReader (const std::string fileName)
:
mFileName (fileName),
mA (42),
mB (314)
{
// something happens like reading the file
}
int GetA () const
{
return mA;
}
int GetB () const
{
return mB;
}
private:
int mA;
int mB;
std::string mFileName;
};
class A
{
private:
const int mA;
const int mB;
public:
A (const FileReader& reader)
:
mA (reader.GetA()),
mB (reader.GetB())
{
}
};
Using this FileReader is simple:
int main()
{
A myA (FileReader ("somefile.txt"));
}
here is my problem: I'm working with two different classes A and B. Class A contains a vector of pointers to objects of type B and I want to use this vector in a function myfunc, which is a member of A. Here is an example
class B {
public:
int x, y;
float z;
// other class members...
};
class A {
public:
// other class members...
vector <B*> myvect;
float myfunc() {
for(size_t i = 0; i < myvect.size(); ++i) cout << myvect[i] -> x << endl;
// rest of the code...
return (some float)
}
};
The program does not compile. It returns an error saying that B is undefined type. It only compiles if I comment out the cout statement. I searched the internet and tried several things, like declaring i as an iterator and dereferencing the iterator, but nothing worked. Any ideas what's wrong with this code?
You can #include "B.h" inside A.h or, the more correct way, have a forward declaration for class B before the definition of A and move the implementation outside of the header:
//B.h
class B
{
//...
};
//A.h
class B; //forward declaration
class A
{
//...
vector <B*> myvect; // <- correct syntax
float myfunc(); // only declaration
//...
};
//A.cpp
#include "A.h"
#include "B.h"
//...
float A::myfunc() { //implementation
for(size_t i = 0; i < myvect.size(); ++i) cout << myvect[i] -> x << endl;
// rest of the code...
return (some float)
}
//..
The compilation error stems from the fact that in your cout statement you are dereferencing the pointer to B. And to do that, the compiler must have a definition of class B available at this point.
In other words, the code like this
pointerToB->x
is valid only if you have #include "B.h" prior to that point.
So, you may either do it in A.h, or, to avoid this extra coupling (and also to avoid large header files), you may want to move such pieces with pointer dereferencing into A.cpp and forward-declare class B in A.h, just as Luchian suggests.
I'd try adding brackets first:
cout << myvect[i] -> x << endl;
to this:
cout << ((myvect[i]) -> x) << endl;
I'll put it at good odds that it's just something simple like that, and that cout is trying to "take" the B* object first, prior to the arrow operator. If that's not it, please post the compiler error messages.
I have the following problem. I have a function from an external library (which cannot be modified) like this:
void externalFunction(int n, void udf(double*) );
I would like to pass as the udf function above a function member of an existing class. Please look at the following code:
// External function (tipically from an external library)
void externalFunction(int n, void udf(double*) )
{
// do something
}
// User Defined Function (UDF)
void myUDF(double* a)
{
// do something
}
// Class containing the User Defined Function (UDF)
class myClass
{
public:
void classUDF(double* a)
{
// do something...
};
};
int main()
{
int n=1;
// The UDF to be supplied is myUDF
externalFunction(n, myUDF);
// The UDF is the classUDF member function of a myClass object
myClass myClassObj;
externalFunction(n, myClassObj.classUDF); // ERROR!!
}
I cannot declare the classUDF member function as a static function, so the last line of the code above results in a compilation error!
This is impossible to do - in c++, you must use either a free function, or a static member function, or (in c++11) a lambda without capture to get a function pointer.
GCC allows you to create nested function which could do what you want, but only in C. It uses so-called trampolines to do that (basically small pieces of dynamically generated code). It would be possible to use this feature, but only if you split some of the code calling externalFunction to a separate C module.
Another possibility would be generating code at runtime eg. using libjit.
So if you're fine with non-reenrant function, create a global/static variable which will point to this and use it in your static function.
class myClass
{
public:
static myClass* callback_this;
static void classUDF(double* a)
{
callback_this.realUDF(a);
};
};
Its really horrible code, but I'm afraid you're out of luck with such a bad design as your externalFunction.
You can use Boost bind or TR1 bind (on recent compilers);;
externalFunction(n, boost::bind(&myClass::classUDF, boost::ref(myClassObj)));
Unfortunately, I lived in a pipe dream for the last 10 minutes. The only way forward is to call the target using some kind of a static wrapper function. The other answers have various neat (compiler-specific) tidbits on that, but here's the main trick:
void externalFunction(int n, void (*udf)(double*) )
{ double x; udf(&x); }
myClass myClassObj;
void wrapper(double* d) { myClassObj.classUDF(d); }
int main()
{
externalFunction(1, &wrapper);
}
std::function<>
Store a bound function in a variable like this:
std::function<void(double*)> stored = std::bind(&myClass::classUDF, boost::ref(myClassObj))
(assuming C++0x support in compiler now. I'm sure Boost has a boost::function<> somewhere)
Vanilla C++ pointers-to-member-function
Without magic like that, you'd need pointer-to-memberfunction syntax:
See also live on http://ideone.com/Ld7It
Edit to clarify to the commenters, obviously this only works iff you have control over the definition of externalFunction. This is in direct response to the /broken/ snippet int the OP.
struct myClass
{
void classUDF(double* a) { };
};
void externalFunction(int n, void (myClass::*udf)(double*) )
{
myClass myClassObj;
double x;
(myClassObj.*udf)(&x);
}
int main()
{
externalFunction(1, &myClass::classUDF);
}
C++98 idiomatic solution
// mem_fun_ref example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
int main ()
{
std::vector<std::string> numbers;
// populate vector:
numbers.push_back("one");
numbers.push_back("two");
numbers.push_back("three");
numbers.push_back("four");
numbers.push_back("five");
std::vector <int> lengths (numbers.size());
std::transform (numbers.begin(), numbers.end(), lengths.begin(),
std::mem_fun_ref(&std::string::length));
for (int i=0; i<5; i++) {
std::cout << numbers[i] << " has " << lengths[i] << " letters.\n";
}
return 0;
}
Here is how I do this, when MyClass is a singleton:
void externalFunction(int n, void udf(double) );
class MyClass
{
public:
static MyClass* m_this;
MyClass(){ m_this = this; }
static void mycallback(double* x){ m_this->myrealcallback(x); }
void myrealcallback(double* x);
}
int main()
{
MyClass myClass;
externalFunction(0, MyClass::mycallback);
}