Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c++ - 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
";
}

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

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

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, e.g.:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A constrained function template only beats an unconstrained function template when they have the same template-parameter-lists and function parameter types. 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
";
}

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
";
    else std::cout << "unknown
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...