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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -