-
-
Save karlnapf/2dd6a23001242cf01a45c99103b736d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CMachine | |
{ | |
public: | |
virtual void train_machine(CFeatures* f) | |
{ | |
// runtime dispatching of feature type | |
switch(f->get_feature_type()) | |
{ | |
case DENSE: | |
train_dense(f); | |
break; | |
case STRING: | |
train_string(f); | |
break; | |
... | |
} | |
} | |
protected: | |
virtual void train_dense(CFeatures f*) | |
{ | |
SG_NOTIMPLEMENTED | |
} | |
virtual bool supports_train_dense() { return false; } | |
... | |
} | |
// Macro to add "centralized" dispatcher for template type to sub-classes | |
#define TRAIN_DENSE_DISPATHER(train_templated_name) \ | |
virtual void train_dense(CFeatures* f) \ | |
{ \ | |
switch (f->get_ptype()) \ | |
{ \ | |
case FLOAT64: \ | |
train_templated_name<float64_t>(f->as<CDenseFeatures<float64_t>>()); \ | |
break; \ | |
... \ | |
} \ | |
} \ | |
virtual bool supports_train_dense() { return true; } | |
class CAlgorithm : public CMachine | |
{ | |
public: | |
TRAIN_DENSE_DISPATHER(my_train_dense_templated) | |
protected: | |
// to be written by developer, compile error if not provided | |
template <class T> | |
void my_train_dense_templated<T>(CDenseFeatures<T> f*) | |
{ | |
// the actual implementation, type-safe | |
} | |
} | |
// for machines that can deal with muultiple feautre types, this is not super elegant | |
// i.e. every feature type that the algorithm supports needs to be explicitly added | |
// instead of working automatically | |
// BUT one can actually sidestep that (see solution below) | |
class CKernelAlgorithm : public CMachine | |
{ | |
public: | |
TRAIN_DENSE_DISPATHER(my_train_dense_templated) | |
TRAIN_STRING_DISPATHER(my_train_string_templated) | |
protected: | |
template <class T> | |
void my_train_dense_templated<T>(CDenseFeatures<T> f*) | |
{ | |
auto K = m_kernel->matrix(f); | |
my_train_using_kernel(K); | |
} | |
template <class T> | |
void my_train_string_templated<T>(CStringFeatures<T> f*) | |
{ | |
auto K = m_kernel->matrix(f); | |
my_train_using_kernel(K); | |
} | |
void my_train_using_kernel(SGMatrix<float64_t> K) | |
{ | |
// feature type independent implementation | |
} | |
} | |
class CKernelAlgorithm2 : public CMachine | |
{ | |
virtual void train_machine(CFeatures* f) | |
{ | |
// feature type independent implementation without going through the dispatcher | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment