我有以下测试案例:
#include <type_traits>
template <typename Ty_>
using conditional_ref =
typename std::conditional<std::is_fundamental<Ty_>::value, Ty_, Ty_ const&>::type;
template <typename Ty_, typename Ty2_ = conditional_ref<Ty_>>
inline void f(Ty2_ arg1) {
static_assert(std::is_same<Ty2_, conditional_ref<Ty_>>::value, "uh-oh!");
}
int main() {
struct A {};
A a{};
double b{};
//f(a); // Cannot deduce parameter (expected)
//f(b); // Cannot deduce parameter (expected)
f<decltype(a)>(a); // uh-oh!
f<decltype(b)>(b); // OK
f<decltype(a), conditional_ref<decltype(a)>>(a); // OK
f<decltype(b), conditional_ref<decltype(b)>>(b); // OK
return 0;
}在这种情况下,f<decltype(a)>将推导为f<A, A>而不是预期的f<A, A const&>。
我试过clang-10、gcc-9和Visual 2019;所有这些都给出了同样的结果,所以我想我做错了什么。
clang-10的输出示例:
$ clang-10 test.cpp
test.cpp:9:3: error: static_assert failed due to requirement 'std::is_same<A, const A &>::value' "uh-oh!"
static_assert(std::is_same<Ty2_, conditional_ref<Ty_>>::value, "uh-oh!");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cpp:19:3: note: in instantiation of function template specialization 'f<A, A>' requested here
f<decltype(a)>(a); // uh-oh!
^
1 error generated.为什么模板演绎不是我在这里所期望的呢?
如何重写f() ,使其在传递基本类型时接受 Ty_ ,而其他情况下则接受 Ty_ const& ?最好只需要传递参数类型一次,比如f<decltype(a)>(a)。
发布于 2021-02-10 16:45:14
通过提供函数调用的参数,推导出Ty2_的类型。可以通过以下方式禁用此扣减
void f(std::type_identity_t<Ty2_> arg1)然后将使用默认模板参数类型。
https://stackoverflow.com/questions/66140737
复制相似问题