我有这样一个函数:
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/