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)
但是,我还没有找到一种方法来做到这一点。有人可以提出来吗?
#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)