Building upon http://www.cplusplus.com/forum/beginner/4639/ I tried adding it to a class. Keep all functions private and have just one public function to access them. Compilation results in:
1 2
undefined reference to `Thing::functions'
collect2.exe: error: ld returned 1 exit status
Without any experience and especially lack of vocabulary I can't find a solution. Why does it go wrong and how should I fix it?
#include <iostream>
class Thing {
private:
// note: const added to make it const-correct
typedefint (Thing::*IntFunc) (int b) const ;
int function(int b) const { return b; }
int functionTimesTwo(int b) const { return b*2; }
int functionDivideByTwo(int b) const { return b/2; }
staticconstexprint NUM_FUNCTIONS = 3 ;
staticconstexpr IntFunc functions[NUM_FUNCTIONS] = {
&Thing::function,
&Thing::functionTimesTwo,
&Thing::functionDivideByTwo
};
public:
int gf(int a, int b) {
if( a >= 0 && a < NUM_FUNCTIONS ) return (this->*functions[a])(b);
elsereturn 0 ; // ideally throw std::out_of_range
}
};
// Prior to C++17:
// If a constexpr static data member is odr-used, a definition at namespace scope
// is still required, but it cannot have an initializer.
constexpr Thing::IntFunc Thing::functions[Thing::NUM_FUNCTIONS] ; // no initialiser
// Since C++17:
// A constexpr static data member is implicitly inline
// and does not need to be redeclared at namespace scope.
// A redeclaration without an initializer (formerly required)
// is still permitted, but deprecated.
// see: https://en.cppreference.com/w/cpp/language/static#Constant_static_membersint main(){
Thing thing;
for(int i = 0; i < 3; ++i) {
constint res = thing.gf(i, 8);
std::cout << res << '\n' ;
}
}