简体   繁体   中英

How can I overload a function for a concept?

Suppose I have a function template and various overloads that "specialize" the template. As overloads are a better match than the template version during overload resolution, they will always get priorized.

template <typename T>
void dispatch(T&& t) {
    std::cout << "generic\n";
}

void dispatch(int) {
    std::cout << "int\n";
}

dispatch(5); // will print "int\n"
dispatch(nullptr); // will print "generic\n";

Now I have the case where I have a specialization that could work for a whole set of (unrelated) types, that however satisfy constraints from a concept, eg:

template <std::floating_point T>
void dispatch(T t) {
    if constexpr(std::is_same_v<T, float>) std::cout << "float\n";
    else std::cout << "unknown\n";
}

Unfortunately, this overload is on par with the generic case, so a call like dispatch(1.0f) is ambiguous. Of course, I could solve this by providing explicit overloads for all types (that I currently know), but as the number of types in my real application is large (and more types of this concept may be added by clients) and the code for each of these types would be very similar (up to small differences that are known at compile-time), this would be a lot of repetition.

Is there a way to overload a function for a whole concept?

A constrained function template only beats an unconstrained function template when they have the same template-parameter-lists . So either make the generic one take a value (so that both take a T ):

template <typename T>
void dispatch(T t) {
    std::cout << "generic\n";
}

Or make the floating point one take a forwarding reference (so that both take a T&& ):

template <typename T>
    requires std::floating_point<std::remove_cvref_t<T>>
void dispatch(T&& t) {
    if constexpr(std::is_same_v<T, float>) std::cout << "float\n";
    else std::cout << "unknown\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM