dv_
dv_

Reputation: 1297

Templated C++ function with the first argument set to the second as default argument

I have a function like this:

template <typename A, typename B>
void foo(const B & b)
{
    ...
}

A should be optional; if not explicitly defined in the function call, it should be set to B. The intent is to avoid unnecessarily verbose code:

int i;

// First variant: A is specified explicitly
foo<float>(i);

// Second variant: A is set to B implicitly
// This is because foo < int > (i) is unnecessarily verbose
foo(i);

However, I haven't found a way to do that yet. Can anybody come up with one?

Upvotes: 5

Views: 279

Answers (1)

Tobi
Tobi

Reputation: 2749

#include <type_traits>

struct deduce_tag;

template <typename PreA = deduce_tag, typename B>
void foo(const B & b) {
    using A = std::conditional_t<
        std::is_same<PreA, deduce_tag>::value,
        B,
        PreA
    >;
}

Upvotes: 9

Related Questions