模板化的C ++函数,第一个参数设置为第二个参数作为默认参数

dv_*_*dv_ 3 c++ templates c++14

我有一个这样的功能:

template <typename A, typename B>
void foo(const B & b)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

A应该是可选的;如果未在函数调用中明确定义,则应将其设置为B。目的是避免不必要的冗长代码:

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);
Run Code Online (Sandbox Code Playgroud)

但是,我还没有找到一种方法来做到这一点。有人可以提出来吗?

Tob*_*obi 6

#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
    >;
}
Run Code Online (Sandbox Code Playgroud)