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

标签 c++ templates c++14

我有这样一个函数:

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

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);

但是,我还没有找到一种方法来做到这一点。有人能想出一个吗?

最佳答案

#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
    >;
}

关于c++ - 第一个参数设置为第二个参数的模板化 C++ 函数作为默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004350/

相关文章:

java - C++ 相当于 Java 的 System.arraycopy

c++ - 与 MySQL 服务器通信的最佳方式是什么?

c++ - 用于脚本定义类型的自定义 RTTI

c++ - 错误 C2064 : term does not evaluate to a function taking 0 arguments

c++ - 来自右值的非常量引用的无效初始化

c++ - 在带有模板参数的模板中使用重载函数

c++ - 在另一个数组中使用一个数组的大小

C++ 模板参数作为引用左值

c++ - 如何将元组插入 map ?

c++ - 如何定义模板函数重载以匹配空 std::tuple<>?