Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

C-style ellipsis fallback

A standalone ellipsis in `test(...)` provides a fallback overload when a typed probe cannot match. It is not a template parameter pack or pack expansion.

Version: ISO C++23; implementation support may vary

Syntax

template<class T>
auto test(const T& value) -> decltype((void)value.size(), std::true_type{});

std::false_type test(...);

A C-style ellipsis fallback such as test(...) is, in this example, a non-template overload with no named parameters. Matching an argument to ... ranks below both standard and user-defined conversion sequences. For the one-argument probes here, the viable test(const T&) therefore wins. The fallback does not resolve ambiguity between better candidates.

In auto test(const T& value) -> decltype(...), -> introduces a trailing return type; it is not pointer member access. If value.size() is well-formed on a const lvalue, the built-in comma in decltype yields the type std::true_type. If that expression is invalid in the immediate context of substitution, SFINAE removes the template specialization from the candidates, leaving test(...) with result type std::false_type. An error in a function body does not trigger this fallback.

class... Ts declares a template type parameter pack, and Ts... in a template argument list expands it into a list of types. In any_has_size, the unary || fold expands a pattern involving Ts, producing one probe result per type. For an empty pack the fold is false; it does not probe test().

Here every call to test is in an unevaluated decltype operand. In an evaluated call through ..., default argument promotions apply, such as float to double. Passing scoped enum values and some class types, such as those with a non-trivial destructor, this way is conditionally supported with implementation-defined semantics. In C++23, test(...) alone cannot portably retrieve its arguments with va_start because it has no preceding named parameter.

Examples

#include <iostream>
#include <type_traits>
#include <utility>

struct Sized {
    int size() const;
};

template<class T>
auto test(const T& value) -> decltype((void)value.size(), std::true_type{});

std::false_type test(...);

template<class... Ts>
constexpr bool any_has_size =
    (... || decltype(::test(std::declval<const Ts&>()))::value);

int main() {
    std::cout << std::boolalpha
              << "mixed: " << any_has_size<int, Sized> << '\n'
              << "int only: " << any_has_size<int> << '\n'
              << "empty: " << any_has_size<> << '\n';
}

Result

mixed: true
int only: false
empty: false

`Sized` passes the probe, `int` does not, and the empty pack gives `false`. Neither `test` nor `Sized::size` is called at runtime, so no definitions are needed.

Related lessons

  • C++ · Lesson 5 · Advanced · Version: 3

Sources