I am Charmie

メモとログ

C++ function pointer

[sourcecode language="cpp"]

template <typename ValueType> struct funcPtr { typedef ValueType (*func)(const ValueType, const ValueType); };

template <typename ValueType> ValueType add( const ValueType a, const ValueType b ) { return a+b; }

template <typename ValueType> ValueType sub( const ValueType a, const ValueType b ) { return a-b; }

template <typename ValueType> ValueType mul( const ValueType a, const ValueType b ) { return a*b; }

template <typename ValueType> ValueType div( const ValueType a, const ValueType b ) { return a/b; }

int main(void) { funcPtr<float>::func fp[4]; fp[0] = add; fp[1] = sub; fp[2] = mul; fp[3] = div; float a = 3.0f, b = 4.0f; for(int n = 0; n < 4; ++n) { std::cout << "fp[" << n << "] = " << fpn << std::endl; } std::vector< funcPtr<int>::func > fp2; fp2.push_back(add); fp2.push_back(sub); fp2.push_back(mul); fp2.push_back(div); for(int n = 0; n < fp2.size(); ++n) { std::cout << "fp2[" << n << "] = " << fp2n << std::endl; }

return 0;

}

[/sourcecode]