c++ - Type checking template class parameters -
i trying achieve type checking of template class parameters disallowing implicit type conversions such string->bool thereby throwing compile error. specific scenario simple 1 follows:
#include <iostream> #include <string> using namespace std; template <class t> class mypair { t a, b; public: mypair(t first, t second ) { = first; b = second; } void test(); }; typedef mypair<bool> boolparm; template<class t> void mypair<t>::test() { if(a == true) { cout << "a true" << endl; } else { cout << "a false" << endl; } if(b == true) { cout << "b true" << endl; } else { cout << "b false" << endl; } } int main() { boolparm myobj(false, "false"); myobj.test(); return 0; }
the output of above scenario undesirable since user may inadvertently pass 2 different types: bool , string , receive first 1 false (correct since passed bool) second 1 true (incorrect since implicit type conversion string bool). wish restrict user code in main() throw compile errors , disallowing string/int parameters pass in constructor. should allow bool. tried using overloaded constructor mypair(bool first, string second) didn't match since guess implicit type conversion string->bool happens before constructor called. there solution using template specializations in scenario? highly appreciated thanks
one workaround add templated factory function create mypair.
template <typename t> mypair<t> makeparam(t a, t b) { return mypair<t>(a, b); }
that fail compile ambiguous template parameter t if types don't match. can extend template specializations explicitly forbidding types t. main function like:
int main() { boolparm myobj = makeparam(false, "false"); myobj.test(); return 0; }
alternatively change constructor:
template <typename u, typename v> mypair(u a, v b);
and specialize necessary
an example of such specialization:
template <class t> class mypair { t a, b; public: template <typename u, typename v> // generic version mypair(u first, v second) { // intentionally fail compile static_assert(false, "don't support generic types"); } template <> // template specialization mypair(t first, t second) { // explicitly require type t = first; b = second; } };
Comments
Post a Comment