jeudi 13 juillet 2017

SFINAE : Know if a function already exist or no

Basically, I want to write code like that :

std::vector<float> a = { 54, 25, 32.5 };
std::vector<int> b = { 55, 65, 6 };

std::cout << a << b << std::string("lol");

It is not possible because there is no overload for operator<<(ostream&, vector)

So, I write a function that do the job :

template<template<typename...> typename T, typename ...Args>
std::enable_if_t<is_iterable_v<T<Args...>>>, std::ostream> &operator<<(std::ostream &out, T<Args...> const &t) {
    for (auto const &e : t)
        out << e << " ";
    out << std::endl;
    return out;
}

That works good, but I have a problem with string. Because strings are iterable and strings HAVE operator<< function.

So I tested with another trait like !is_streamable_out && _is_iterable testing something like that : std::declval<std::ostream&>() << std::declval<T>() and if it has begin / end functions. It works good on MSVC, but not on Clang (I think it is because the compiler use the function I just create as well, so it founds one overload available for all methods).

So, I am currently using !is_same_v<string, T> but it is not perfect IMHO.

Is there a way to know if a function exists without redeclaring the function?

Basically, I want to do something like that

if function foo does not exist for this type.
then function foo for this type is ...

Aucun commentaire:

Enregistrer un commentaire