vendredi 15 mai 2020

How to conditionally define a variable in method call using SFINAE?

I want to define a template class IE which provides public method(). method() calls underlying private run(), which may take arguments related to template parameters passed to IE. So:

  • For IE<void>, run() without arguments is executed.
  • For any other T in IE<T>, run(vector<T>) is executed.

I think I correctly SFINAE'd method run(), but I have problem with defining the parameter that should be passed to run. I came up with defining Extra in the presented way, but I get errors that T can't be deduced.

template<typename X=void>
class IE
{
    template<typename T=void>
    struct Extra;

    template<typename T>
    struct Extra<enable_if_t<is_void<T>::value, T>> {};

    template<typename T>
    struct Extra<enable_if_t<!is_void<T>::value, T>>
    {
        std::vector<T> ex;
    };

    template<typename X_=X>
    void run(enable_if_t<is_void<X_>::value , Extra<X_>> x) {
        cout << "In run" << endl;
    }

    template<typename X_ = X>
    void run(enable_if_t<!is_void<X_>::value , Extra<X_>> x)
    {
        cout << "In run: X=" << x.ex.size() << endl;
    }

public:
    void method()
    {
        Extra<X> x;
        run(x);
    }
};

int main() {
    IE<double> ie1;
    ie1.method(); // should execute run(vector<double>)

    IE<> ie2;
    ie2.method(); // should execute run()
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire