gpt4 book ai didi

c++ - 为什么 std::add_lvalue_reference 的行为不如预期?

转载 作者:行者123 更新时间:2023-11-30 03:19:28 25 4
gpt4 key购买 nike

#include <type_traits>

template<typename T>
using Ref1 = T & ;

template<typename T>
using Ref2 = std::add_lvalue_reference_t<T>;

template<typename T>
void f1(Ref1<T>)
{}

template<typename T>
void f2(Ref2<T>)
{}

int main()
{
int n{};
f1(n); // ok
f2(n); // error
}

我的编译器是clang 7.0,用c++17编译。错误信息是:

error : no matching function for call to 'f2'
note: candidate template ignored:
couldn't infer template argument 'T'

为什么 f1 可以,但 f2 不行?

最佳答案

std::add_lvalue_reference_t<T> 定义为 typename std::add_lvalue_reference<T>::type , 然后为 template<typename T> void f2(Ref2<T>) ,即 template<typename T> void f2(typename std::add_lvalue_reference<T>::type) , 属于 non-deduced context ,这会导致模板参数推导失败。

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:

关于c++ - 为什么 std::add_lvalue_reference 的行为不如预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53679047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com