samedi 27 août 2022

How to pass reference of noncopyable type to SFINAE "catch-all" overload function?

I need to check data type, but can't handle the noncopyable class. Now I use pointer instead of references. Is there a better way?

#include <iostream>
#include <functional>

template <typename T, std::enable_if<std::is_integral<T>::value, bool> = true>
void data_type(T const& t) {
    std::cout << "integer" << std::endl;
}

void data_type(...) {
    std::cout << "unknown" << std::endl;
}

int main() {
    struct noncopyable_type {
        noncopyable_type() {}
        noncopyable_type(const noncopyable_type&) = delete;
    };

    int i;
    noncopyable_type s;

    // first try
    data_type(i);   // ok
    data_type(s);   // error: call to deleted constructor

    // try again
    data_type(std::cref(i)); // ok, but the type is std::reference_wrapper, not integer
    data_type(std::cref(s)); // ok
}

Aucun commentaire:

Enregistrer un commentaire