-
Notifications
You must be signed in to change notification settings - Fork 1
Description
TLDR; Consider optimizing build-time for all single-argument templated constructors, and assignment operators by early-out with an SFINAE !is_same<std::remove_cv_ref_t<Arg>, expected>
Long story:
When instantiating a class that wraps (or derives from) expected<T, E>, it usually must determine whether expected is copyable/moveable via appropriate type traits.
Compiler/std lib does this internally by performing overload resolution e.g. for expected<T, E>(const expected&) which triggers template argument substitution for all constructors with matching parameters list, including the ones that will never be selected because they are templates (on tie template function always lose to non-template function).
Template argument substitution can be quite costly when it involves complex SFINAE expressions like enable_from_other_expected_t.
We can optimize such scenarios by short-circuting the SFINAE checks for given template function in case it would match parameters of one of SMFs.
gcc 9+ already optimizes such scenarios internally, but latest clang still doesn't.
Example below illustrates the problem and a workaround:
#include <type_traits>
template <typename T>
constexpr auto busyLoop()
{
unsigned sum = 0u;
unsigned arr[200'000] = {};
for (auto c : arr)
{
sum += c * c / (c + 1u) ^ c;
}
return sum == 0;
}
template <typename T>
constexpr bool some_complex_condition_v = busyLoop<T>();
template <typename T>
struct Foo
{
Foo(const Foo&) = delete;
#ifndef WORKAROUND
template <typename U, std::enable_if_t<some_complex_condition_v<U>> * = nullptr>
Foo(const U&);
#else
template <typename U, std::enable_if_t<!std::is_same_v<U, Foo>>* = nullptr, std::enable_if_t<some_complex_condition_v<U>> * = nullptr>
Foo(const U&);
#endif
};
static_assert(!std::is_copy_constructible_v<Foo<int>>);On my machine with clang-20 following code compiles in about ~1.3s, while it takes <0.1s when compiled with -DWORKAROUND