gpt4 book ai didi

c++ - foo 的调用没有匹配函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:44 25 4
gpt4 key购买 nike

为什么下面的代码会出现构建错误

编译器使用c++14 xcode 8.3.3

#include <iostream>
#include <array>

template<typename T, typename U>

void foo(std::array<T,sizeof(U)> x,
std::array<U,sizeof(T)> y,
int z)
{

puts(__PRETTY_FUNCTION__);
}

int main()
{

foo(std::array<int,8>{},std::array<double,4>{},1);
foo(std::array<int,9>{},std::array<double,4>{},2);

}

错误第二次调用出错

foo(std::array<int,9>{},std::array<double,4>{},2);

DEMO

g++ -std=c++1z -fconcepts -fgnu-tm  -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic -lstdc++fs && ./a.out
main.cpp: In function 'int main()':
main.cpp:18:14: error: could not convert 'std::array<int, 9>{}' from 'std::array<int, 9>' to 'std::array<int, 8>'
foo(std::array<int,9>{},std::array<double,4>{},2);
^~~~~~~~~~~~~~
main.cpp: In instantiation of 'void foo(std::array<T, sizeof (U)>, std::array<U, sizeof (T)>, int) [with T = int; U = double]':
main.cpp:17:53: required from here
main.cpp:6:34: warning: unused parameter 'x' [-Wunused-parameter]
void foo(std::array<T,sizeof(U)> x,
^
main.cpp:7:34: warning: unused parameter 'y' [-Wunused-parameter]
std::array<U,sizeof(T)> y,
^
main.cpp:8:14: warning: unused parameter 'z' [-Wunused-parameter]
int z)
^

但是如果只有一个调用就可以了

#include <iostream>
#include <array>


template<typename T, typename U>

void foo(std::array<T,sizeof(U)> x,
std::array<U,sizeof(T)> y,
int z)
{

puts(__PRETTY_FUNCTION__);
}


int main()
{

foo(std::array<int,8>{},std::array<double,4>{},1);
//foo(std::array<int,9>{},std::array<double,4>{},2);

}

输出

void foo(std::array<T, sizeof(U)>, std::array<U, sizeof(T)>, int) [T = int, U = double]
Program ended with exit code: 0

最佳答案

您的问题在于:

foo(std::array<int,9>{},std::array<double,4>{},2);

为了理解错误,让我们尝试做“编译器工作”并尝试理解模板函数是如何工作的foo被称为。

所以。

函数foo有两种推导类型:TU .

当您调用 foo 时使用该语句,您将传递两个参数:

  • std::array<int, 9>
  • std::array<double, 4>

并且您的模板函数接受:

  • std::array<T,sizeof(U)> x
  • std::array<U,sizeof(T)> y

所以很容易看出T映射为 intU作为double .

推导函数将变为:

void foo(std::array<int, 8>,
std::array<double, 4>,
int);

因为很可能在你的架构上sizeof(double) = 8sizeof(int) = 4 (我刚刚替换了 sizeof s)。

所以你的调用是错误的,因为你的第一个参数是std::array<int, 9>而不是 std::array<int, 8> .

的确,你之前的电话:

foo(std::array<int,8>{},std::array<double,4>{},1);

编译。

关于c++ - foo 的调用没有匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45774557/

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