Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SFINAE to disable template class member function

Tags:

c++

sfinae

c++14

Is it possible to use SFINAE and std::enable_if to disable a single member function of a template class?


I currently have a code similar to 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 to 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 be disabled if T != int. Because f is virtual, Derived<T>::f() gets generated for any instantiation of Derived, even if it is never called. But the code is used such that Derived<T> (with T != int) never gets created only as a base class of MoreDerived<T>.

So the hack in Derived<T>::f() is necessary to make the program compile; the reinterpret_cast line never gets executed.

like image 385
tmlen Avatar asked Jul 28 '16 12:07

tmlen


2 Answers

You could simply specialize f for 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_();
}
like image 56
Holt Avatar answered Sep 30 '22 19:09

Holt


No you can't rule out a member function with SFINAE. You could do it with specialisation of your Derived class f member function for convertible Ts to int but that would lead to unnecessary duplication of code. In C++17 however you could solve this with use of if constexpr:

template<typename T> class Derived : public Base {
  T getValue_() { return T(); }
public:
  int f() override {
    if constexpr(std::is_convertible<T, int>::value) return getValue_();
    return Base::f();
  }
};

Live Demo

like image 45
101010 Avatar answered Sep 30 '22 19:09

101010