"no matching function for call to [...] cdk::sequence_node*&"
What kind of sorcery is this? How do I fix it? Do I have to cast?
Function expects cdk::sequence_node * some_sequence_node as argument.
According to this question about asterisk and ampersand
BinaryNode b;
BinaryNode* ptr = &b;
BinaryNode* &t = ptr;
Why is the compiler complaining if BinaryNode* &t = ptr;?
Edit (as requested):
pwn_parser.y: In function ‘int yyparse(std::shared_ptr<cdk::compiler>)’:
pwn_parser.y:70:135: error: no matching function for call to ‘pwn::func_decl_node::func_decl_node(int, bool, bool, basic_type*&, std::string*&, cdk::sequence_node*&)’
func_decl : type_specifier tIDENTIFIER '(' func_decl_args ')' context { $$ = new pwn::func_decl_node(LINE, false, false, $1, $2, $4); }
pwn_parser.y:70:135: note: candidates are:
In file included from ast/all.h:99:0,
from pwn_parser.y:5:
./ast/func_decl_node.h:29:12: note: pwn::func_decl_node::func_decl_node(int, bool, bool, basic_type*, cdk::identifier_node*, cdk::sequence_node*)
inline func_decl_node(int lineno, bool local, bool import,
Thanks to dyp, who helped me notice a little mismatch that I had overlooked, I was able to fix it.
Oops, correct. However, you're passing a std::string* where a identifier_node* is expected (for the overload shown by the compiler as a candidate). - by dyp
Lesson 1: Don't make the mistake of looking at a problem as if it was a huge monster or fire blowing wide winged dragon blocking your way. Picture the problem as always being smaller than yourself. Funny Awkward Yeti Comic
Lesson 2: Don't make the assumption that some part of the information is irrelevant.
Related
I have a type A that's designed to be implicitly casted to type B. Here's an example case I'd like to use it in:
// Current implementation:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
[](const A& a) -> B { return a; }); // Thanks, Kerrek SB.
// Ideal implementation - Won't compile, expected '(' after 'static_cast'.
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
static_cast<B>);
What can I do to make the latter option compile?
static_cast<B>, while it is invoked with function-call syntax cannot be passed like other callable things. E.g., there's no way to use & to get a function pointer to it.
You can use a short little lambda to achieve something similar to passing a function pointer to static_cast<B>, as you do in your current implementation:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
[](const A& a) -> B { return a; });
Another option--in this particular case--would be to construct a vector<B> from the vector<A>:
std::vector<B> vec_of_b(vec_of_a.begin(), vec_of_a.end());
(This answer is a summary of the comments on both the question and bipll's answer.)
Build a functor enclosing static_cast:
template <typename T>
struct StaticCast
{
template <typename U>
T operator()(const U& rhs)
{
return static_cast<T>(rhs);
}
};
With this, you can call std::transform:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b), StaticCast<b>());
It can be used in the case the output vector is already defined in place of the lambda shown in comments. If not, prefer the constructor mentioned in another answer**.
This functor version is compliant with C++98 if needed -- even if OP is tagged C++11, it may be worthy to note this point.
** Note that with this particular constructor, a warning C4244 is raised with VS compiler (tested with VS2017).
Yes, that's the way anonymous functions work in C++, and static_cast is not a function so you cannot pass its address as the mapped function. You'll have to deal with it.
You cannot use a constructor either.
While the Swift compiler (Xcode 7.2) seems perfectly correct in diagnosing an error for some source text equivalent to the following, it took long to detect the actual error made. Reason: the programmer needs to look not at the text marked, but elsewhere, thus mislead, wondering why an optional string and a non-optional string can not be operands of ??...
struct Outer {
var text : String
}
var opt : String?
var context : Outer
context = opt ?? "abc"
Obviously, the last line should have had context.text as the variable to be assigned. This is diagnosed:
confusion2.swift:9:19: error: binary operator '??' cannot be applied\
to operands of type 'String?' and 'String'
context = opt ?? "abc"
~~~ ^ ~~~~~
The message is formally correct. (I am assuming that type checking the left hand side establishes an expected type (Outer) for the right hand side, and this, then, renders the expression as not working, type-wise.) Taken literally, though, the diagnosis is wrong, as is seen when fixing the left hand side: ?? can be applied to operands of type String? and String.
Now, if this is as good as it gets, currently, in terms of compiler messages, what are good coping strategies? Is remembering
Type inference!
Context!
…
a start? Is there a more systematical approach? A check list?
Update (I'm adding to the list as answers come in. Thanks!)
break statements apart, so as to have several lines checked separately (#vacawama)
Beware of optionals (such as values got from dictionaries), see testSwitchOpt below
Another one
enum T {
case Str(String)
case Integer(Int)
}
func testSwitchOpt(x : T?) -> Int {
switch x {
case .Integer(let r): return r
default: return 0
}
}
The compiler says
optandswitch.swift:8:15: error: enum case 'Integer' not found in type 'T?'
case .Integer(let r): return r
A fix is to write switch x! (or a more cautious let), so as to make type checking address the proper type, I guess.
I could, perhaps should, file some report at Apple, but the issue seems to represent a recurring subject—I have seen this with other compilers—and I was hoping for some general and re-usable hints, if you don't mind sharing them.
Swift's type inference system is great in general, but it can lead to very confusing to outright wrong error messages.
When you get one of these Swift error messages that makes no sense, a good strategy is to break the line into parts. This will allow Swift to return a better error message before it goes too far down the wrong path.
For example, in your case, if you introduce a temporary variable, the real problem becomes clear:
// context = opt ?? "abc"
let temp = opt ?? "abc"
context = temp
Now the error message reads:
Cannot assign value of type 'String' to type 'Outer'
Context
Assessment piece for a data structures and algorithms course, an exercise in using an AVL tree and hash table to parse input to create a dictionary file and then use that file to perform cursory spell checking.
N.B.: I am not asking for help in solving this problem that's not what I'm having difficulty with. I am asking for help understanding an aspect of C++ function object passing/usage that is causing me considerable frustration. This aspect of C++ is not part of the assessment, there are no marks attached to it, I simply have a personal issue submitting code I dislike the design of.
Problem
Passing a functor to a recursive function results in compiler error, "attempt to use a deleted function." I thought this was an issue with passing the functor by value, so I changed the parameter to pass by reference which yields a, "no matching member function for call to <public member function of AVL tree that kicks off the recursion>," in which case I don't know how to alter the function declaration so it does match. I have also tried making the parameter: const UnaryFunction& action (a constant function-object reference), but this yields the compiler error, "no matching function for call to object of type 'const std::__1::__mem_fn<void (DictGen::*)(std::__1::basic_string<char> &)>'," in which case I can't understand why it wouldn't be matching to the DictGen::output signature.
Code
Relevant parts of AVL tree class:
template <class T>
struct AVLNode
{ // simple data carrier node for AVL tree
AVLNode<T>* lChild;
AVLNode<T>* rChild;
AVLBalance balFac;
T data;
};
template <class T>
class AVLTree<T>
{
...
AVLNode<T>* root;
template <class UnaryFunction>
void inorderAction( AVLNode<T>* node, UnaryFunction action )
{
if ( node != NULL )
{
inorderAction( node->lChild, action );
action( node->data ); // << problem line
inorderAction( node->rChild, action );
}
}
public:
template <class UnaryFunction>
void inorder( UnaryFunction action )
{
inorderAction( root, action );
}
}
Relevant parts of DictGen class:
class DictGen
{
...
FILE* outStream;
AVLTree<std::string> dict;
void output( std::string& word )
{
fprintf( outstream, "%s\n", word.c_str() );
}
public:
goGoGadgetDictionaryGenerator()
{
...
dict.inorder( std::mem_fn( &DictGen::output ) ); // << also problem line
}
}
Interpretation/Translation
AVL tree class has a flexible inorder traversal that allows me to action the node however I want with the given UnaryFunction action. A DictGen object is initialised with a FILE* so DictGen instances may output to different files, hence the need to pass a member function object in the dict.inorder( ... ) call.
Efforts/research so far
My initial solution was to follow the functions as parameters example given in our textbook which involved using C function pointers and polluting global space. Although this worked I was unsatisfied with this design; I wished to bundle this behaviour in a DictGen class.
My after consulting both my lecturer and lab tutor they suggested using C++ functors but weren't able to help with implementation as neither had used functors in a while.
I forged ahead finding very handy material on SO (helping me reference a member function), several functor tutorials via Google and an excellent PDF from a Stanford course regarding functor implementation and usage. However, while all these resources have carried me this far, none have been able to shed any light on my current predicament. I was really hoping making the parameter a const UnaryFunction& would solve it but can't understand why the signature doesn't match.
I have also tried using an inline lambda but require the object context to access outStream.
I have spent the last four days ploughing away at this issue and the only remaining lead I have is an SO post that casually remarked that the C++ spec contains information about the implicit deletion of function objects but I haven't been able to make any further progress. If there is an SO post that solves my issue, I haven't been able to find it.
Questions
Does the recursion really have anything to do with this issue?
Is there some novice aspect of functor passing/usage I'm not grasping?
What is causing the function to be deleted?
What am I missing about getting the function signatures to match when it appears that function deletion isn't the issue?
This is my very first SO post, I have done my best to keep the question-asking suggestions in mind. I welcome any constructive criticism to help me improve this post so that I can it can both solve my issue and serve as a future resource for similar issues.
You need to have an instance of DictGen bound to the member function:
// ...
void gen()
{
dict.inorder(
std::bind( std::mem_fn( &DictGen::output ),
this, std::placeholders::_1) );
}
// ...
You are coding in C++11. While there are uses for std::mem_fn and std::bind, they are a very awkward way to generate these kind of functors.
void gen()
{
dict.inorder(
[this]( std::string& word ) { this->output(word); }
);
}
while the lambda syntax might be somewhat new to you, this is far less backwards than the std::bind( std::mem_fn( &T::method ), this, std::placeholders::_1)
The basic syntax of a lambda is:
[capture-list]( arguments )->return value { code }
where capture-list is [=] (auto-capture by value) or [&] (auto-capture by reference) or [var1, var2] (capture var1 and var2 by value) or [&var1, &var2] (capture var1 and var2 by reference) or a mixture of same. (C++1y adds new syntax, like [x = std::move(y)])
(arguments) are just a usual function argument bit. It is actually optional, but required if you want a return value.
-> return value is optional for single-statement lambdas, or lambdas that return void. (In C++1y, it is optional even with multiple returns)
Then the code.
I want to know data type using variable name
My final goal is getting a function signature for making a function stub(skeleton code)
but GCC error message just notify only undefined function name
Can I see a symbol table? (for inferencing function signature)
for example, foo.c is like below
#include <stdio.h>
int main() {
int n = 0;
n = foo();
return 0;
}
I want to make a function stub
so I want to know function foo has no parameter and returns an integer value
What should I do?
I think below:
linker error message say function foo is undefined
read line 5
n = foo();
inspect type of n using symbol table
is it right?
sorry for my bad english
please teach me inferencing a function signature
Inject his code into your source file:
typedef struct { int a; char c; } badtype_t;
badtype_t badtype;
then replace the error line like this:
n = badtype; //foo();
or if you want the type foo returns:
badtype = foo();
then you will get some error like this:
incompatible types when initializing type ‘int’ using type ‘badtype_t’
and you can get the type int.
or if you want the type of foo itself:
foo * 2
then you will get some error like this:
invalid operands to binary * (have 'int (*)()' and 'int')
and you can get the type int (*)() (that is, function taking nothing and returning an int).
It seems ok, but this strategy will not be good enough. Using the left-hand side of an expression is not enough to determine the return-type of the function. In particular, there may be no left-hand side at all, simply: foo();. What then?
If you just want to see a symbol table, that's what nm is for.
For example, if you get an error linking foo.o and bar.o together, you can do this:
nm -a foo.o
That will show you all the symbols defined in module foo.
But I don't see why you think this would help. C symbols do not have any type information. There may be enough metadata to distinguish extern linkage, and/or to tell whether a symbol function or data, but that's it. There is no way to tell an int from a float, or a function taking two ints and returning a double from a function taking a char * and returning a different char *.
So, you have some function named foo defined somewhere, and you want to know what its type is.
If you don't actually have a prototype for foo somewhere in your #included header files, this is easy:
If you're using C99, your code is invalid.
Otherwise, foo must take no arguments and return int, or your code is invalid.
And this isn't one of those "technically invalid, but it works on every platform" cases; it will break. For example, with gcc 4.2 for 64-bit x86 linux or Mac, if you do this:
double foo(double f) { return f*2; }
Then, without a header file, call it like this:
double f = foo(2.0);
printf("%f\n", f);
If compiled as C89, this will compile and link just fine (clang or gcc 4.8 will give you a warning; gcc 4.2 won't even do that by default), and run, and print out 2.0. At least on x86_64; on ARM7, you'll corrupt the stack, and segfault if you're lucky. (Of course it actually does double something—either your 2.0 or some random uninitialized value—but it can't return that to you; it's stashed it in an arbitrary floating-point register that the caller doesn't know to access.)
If it is in a header file, you can always search for it. emacs, graphical IDEs, etc. are very good at this. But you can use the compiler to help you out, in two ways.
First, just do this:
gcc -E main.c > main.i
less main.i
Now search for /foo, and you'll find it.
Or you can trick the compiler into giving you an error message, as in perreal's answer.
struct STest : public boost::noncopyable {
STest(STest && test) : m_n( std::move(test.m_n) ) {}
explicit STest(int n) : m_n(n) {}
int m_n;
};
STest FuncUsingConst(int n) {
STest const a(n);
return a;
}
STest FuncWithoutConst(int n) {
STest a(n);
return a;
}
void Caller() {
// 1. compiles just fine and uses move ctor
STest s1( FuncWithoutConst(17) );
// 2. does not compile (cannot use move ctor, tries to use copy ctor)
STest s2( FuncUsingConst(17) );
}
The above example illustrates how in C++11, as implemented in Microsoft Visual C++ 2012, the internal details of a function can modify its return type. Up until today, it was my understanding that the declaration of the return type is all a programmer needs to know to understand how the return value will be treated, e.g., when passed as a parameter to a subsequent function call. Not so.
I like making local variables const where appropriate. It helps me clean up my train of thought and clearly structure an algorithm. But beware of returning a variable that was declared const! Even though the variable will no longer be accessed (a return statement was executed, after all), and even though the variable that was declared const has long gone out of scope (evaluation of the parameter expression is complete), it cannot be moved and thus will be copied (or fail to compile if copying is not possible).
This question is related to another question, Move semantics & returning const values. The difference is that in the latter, the function is declared to return a const value. In my example, FuncUsingConst is declared to return a volatile temporary. Yet, the implementational details of the function body affect the type of the return value, and determine whether or not the returned value can be used as a parameter to other functions.
Is this behavior intended by the standard?
How can this be regarded useful?
Bonus question: How can the compiler know the difference at compile time, given that the call and the implementation may be in different translation units?
EDIT: An attempt to rephrase the question.
How is it possible that there is more to the result of a function than the declared return type? How does it even seem acceptable at all that the function declaration is not sufficient to determine the behavior of the function's returned value? To me that seems to be a case of FUBAR and I'm just not sure whether to blame the standard or Microsoft's implementation thereof.
As the implementer of the called function, I cannot be expected to even know all callers, let alone monitor every little change in the calling code. On the other hand, as the implementer of the calling function, I cannot rely on the called function to not return a variable that happens to be declared const within the scope of the function implementation.
A function declaration is a contract. What is it worth now? We are not talking about a semantically equivalent compiler optimization here, like copy elision, which is nice to have but does not change the meaning of code. Whether or not the copy ctor is called does change the meaning of code (and can even break the code to a degree that it cannot be compiled, as illustrated above). To appreciate the awkwardness of what I am discussing here, consider the "bonus question" above.
I like making local variables const where appropriate. It helps me clean up my train of thought and clearly structure an algorithm.
That is indeed a good practice. Use const wherever you can. Here, however, you cannot (if you expect your const object to be moved from).
The fact that you declare a const object inside your function is a promise that your object's state won't ever be altered as long as the object is alive - in other words, never before its destructor is invoked. Not even immediately before its destructor is invoked. As long as it is alive, the state of a const object shall not change.
However, here you are somehow expecting this object to be moved from right before it gets destroyed by falling out of scope, and moving is altering state. You cannot move from a const object - not even if you are not going to use that object anymore.
What you can do, however, is to create a non-const object and access it in your function only through a reference to const bound to that object:
STest FuncUsingConst(int n) {
STest object_not_to_be_touched_if_not_through_reference(n);
STest const& a = object_not_to_be_touched_if_not_through_reference;
// Now work only with a
return object_not_to_be_touched_if_not_through_reference;
}
With a bit of discipline, you can easily enforce the semantics that the function should not modify that object after its creation - except for being allowed to move from it when returning.
UPDATE:
As suggested by balki in the comments, another possibility would be to bind a constant reference to a non-const temporary object (whose lifetime would be prolonged as per § 12.2/5), and perform a const_cast when returning it:
STest FuncUsingConst(int n) {
STest const& a = STest();
// Now work only with a
return const_cast<STest&&>(std::move(a));
}
A program is ill-formed if the copy/move constructor [...] for an object is implicitly odr-used and the special member function is not accessible
-- n3485 C++ draft standard [class.copy]/30
I suspect your problem is with MSVC 2012, and not with C++11.
This code, even without calling it, is not legal C++11:
struct STest {
STest(STest const&) = delete
STest(STest && test) : m_n( std::move(test.m_n) ) {}
explicit STest(int n) : m_n(n) {}
int m_n;
};
STest FuncUsingConst(int n) {
STest const a(n);
return a;
}
because there is no legal way to turn a into a return value. While the return can be elided, eliding the return value does not remove the requirement that the copy constructor exist.
If MSVC2012 is allowing FuncUsingConst to compile, it is doing so in violation of the C++11 standard.