# Pointer to member function in template class

I want to eliminate the process consumed by a decision using pointers to member functions. I need to give user options to turn on or off domain checking for a function defined on a limited continues domain.

It's ok to have pointers to member functions when not using templates. But here I have to generalize my implementation.

Specifically I have three member functions in my class:

1.value is a member function returns value calculated by the member that function points to. The function is a function pointer wich points to either checkedValue or uncheckedValue. 2.checkedValue is a member function that calculates and returns the result, if input is in specified range. else throws a std::domain error. 3.uncheckedValue calculates and returns the result, regardless of domain.

template <typename T> class IO { private: typedef T (IO<T>::*functionPtr)(const std::string& name, const T& input) const; functionPtr function; bool domainValidation; void setDomainValidation(const bool& value); //... public: // ... T value(const std::string& name, const T& input) const; T uncheckedValue(const std::string& name, const T& input) const; T checkedValue(const size_t& index, const T &input) const; }; // Implementation: template <typename T> void IO<T>::setDomainValidation(const bool &value) { domainValidation = value; if(domainValidation) { // function points to checkedValue() function = & IO<T>::checkedValue; // Here I got undefinded reference error } else { // function points to uncheckedValue() } } template <typename T> T IO<T>::value(const string &name, const T &input) const { return (this->*function)(name,input); } template <typename T> T IO<T>::uncheckedValue(const string &name, const T &input) const { // simply calculate and return the result } template <typename T> T IO<T>::checkedValue(const string &name, const T &input) const { // if input is in domain, calculate and return the result // else throw a std::domain error }

## Answers

Your function has signature

T checkedValue(const size_t& index, const T &input) const;

but not

T IO<T>::checkedValue(const string &name, const T &input) const;

Note the difference between the types of the first parameter.

This looks like a typo to me: The function signature of the function pointer is

...(const std::string &, const T &) ...

The signature of checkedValue is

...(const size_t &, const & T) ...

If the signature is changed to match the function pointer, the code sample compiles for me. Concerning the performance: Are you sure (as in have profiled or looked at the assembly) that the simple if-clause inside the value-method is worse than the (possible) indirection through a function pointer? Obviousl, the call to checked or uncheckedValue cannot be inlined.