J
Justin Piper
I was toying with using function pointers to implement a state machine,
and ran into trouble when I tried to use a template to specify the type
of one of the arguments. I was able to determine that I need to
explicitly cast a pointer to a template function to the correct type,
and I was hoping someone could explain why this is necessary. I have
included a minimal example exhibiting the problem below. It was
compiled using the MinGW port of g++ 3.4.2 on W2kSP4.
#include <iostream>
struct evaluator {
bool (*eval)(evaluator&);
};
template <typename T>
bool stop(T &e) { return true; }
bool eval(evaluator &e) { return true; }
int main() {
typedef bool (*evalf)(evaluator&);
struct evaluator e = { stop<evaluator> };
// error: assuming cast to type 'bool (*)(evaluator&)' from
// overloaded function
std::cout << (e.eval == stop<evaluator>) << '\n';
// ok--eval is not templated
std::cout << (e.eval == eval) << '\n';
// ok--explicitly cast to correct type
std::cout << (e.eval == static_cast<evalf>(stop<evaluator>)) <<
'\n';
return 0;
}
and ran into trouble when I tried to use a template to specify the type
of one of the arguments. I was able to determine that I need to
explicitly cast a pointer to a template function to the correct type,
and I was hoping someone could explain why this is necessary. I have
included a minimal example exhibiting the problem below. It was
compiled using the MinGW port of g++ 3.4.2 on W2kSP4.
#include <iostream>
struct evaluator {
bool (*eval)(evaluator&);
};
template <typename T>
bool stop(T &e) { return true; }
bool eval(evaluator &e) { return true; }
int main() {
typedef bool (*evalf)(evaluator&);
struct evaluator e = { stop<evaluator> };
// error: assuming cast to type 'bool (*)(evaluator&)' from
// overloaded function
std::cout << (e.eval == stop<evaluator>) << '\n';
// ok--eval is not templated
std::cout << (e.eval == eval) << '\n';
// ok--explicitly cast to correct type
std::cout << (e.eval == static_cast<evalf>(stop<evaluator>)) <<
'\n';
return 0;
}