c++ - Using SFINAE to disable template class member function -
is possible use sfinae , std::enable_if disable single member function of template class?
i have code similar this:
#include <type_traits> #include <iostream> #include <cassert> #include <string> class base { public: virtual int f() { return 0; } }; template<typename t> class derived : public base { private: t getvalue_() { return t(); } public: int f() override { assert((std::is_same<t, int>::value)); t val = getvalue_(); //return val; --> not possible if t not convertible int return *reinterpret_cast<int*>(&val); } }; template<typename t> class morederived : public derived<t> { public: int f() override { return 2; } }; int main() { derived<int> i; morederived<std::string> f; std::cout << f.f() << " " << i.f() << std::endl; } ideally, derived<t>::f() should disabled if t != int. because f virtual, derived<t>::f() gets generated instantiation of derived, if never called. code used such derived<t> (with t != int) never gets created base class of morederived<t>.
so hack in derived<t>::f() necessary make program compile; reinterpret_cast line never gets executed.
you specialize f int:
template<typename t> class derived : public base { private: t getvalue_() { return t(); } public: int f() override { return base::f(); } }; template <> int derived<int>::f () { return getvalue_(); }
Comments
Post a Comment