At start I will point that I did spare a lot of time trying to find the answer online, I even asked chat GPT 4 to explain me this issue but it wasn’t able to give me the answer, so please don’t downvote – you guys are really my last hope! <3
Here is the most basic example of the C++ code that raises this compilation error:
template <typename T>
void TestF(int(*func)(const T&)) {
}
int IntNormal(const int& x) {
return x;
}
int IntPointer(const int*& x) {
return *x;
}
int main() {
TestF<int>(IntNormal); //Works just fine
TestF<int*>(IntPointer); //Gives compilation error
return 0;
};
The error Intellisense gives me is :
Error (active) E0304 no instance of function template "TestF" matches the argument list
Error C2664 'void TestF<const int*>(int (__cdecl *)(const T &))': cannot convert argument 1 from 'int (__cdecl *)(const int *&)' to 'int (__cdecl *)(const T &)'
with
[
T=const int *
]
I just don’t understand why it works just fine with normal int but it doesn’t with pointer to int, even though it looks as if I was using correct method signature..
Thank you in advance for help! <3
EDIT: I have been advised to write what I wanted to achieve:
I just need a template method that works both with pointers and with normal types. I am using this code for my own data structures but I was getting an error. I managed to isolate the issue to this simple example.
12
At first I wanted to thank Drew Dormann for his link:
What is the difference between const int*, const int * const, and int * const?
I have read this and managed to write working code:
template <typename T>
void TestF(int(*func)(const T&)) {
}
int IntNormal(const int& x) {
return x;
}
int IntPointer(int*const& x) { //Here is fix - I write int * const & instead of const int * &
return *x;
}
int main() {
TestF<int>(IntNormal); //Works just fine
TestF<int*>(IntPointer); //Now works after above fix
return 0;
};
5