gpt4 book ai didi

具有隐式参数的 C++ 函数模板实例化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:26 26 4
gpt4 key购买 nike

我不明白为什么下面的代码可以正常编译:

#include <iostream>                                                                 

void bar(int x) {
std::cout << "int " << x << std::endl;
}

void bar(double x) {
std::cout << "double " << x << std::endl;
}

template <typename A, typename B> // Note the order of A and B.
void foo(B x) {
bar((A)x);
}

int main() {
int x = 1;
double y = 2;

foo<int>(x); // Compiles OK.
foo<double>(y); // Compiles OK.

return 0;
}

但是如果我如下调换 AB 的顺序,那么它不会编译:

#include <iostream>                                                                 

void bar(int x) {
std::cout << "int " << x << std::endl;
}

void bar(double x) {
std::cout << "double " << x << std::endl;
}

template <typename B, typename A> // Order of A and B are switched.
void foo(B x) {
bar((A)x);
}

int main() {
int x = 1;
double y = 2;

foo<int>(x); // error: no matching function for call to ‘foo(int&)’
foo<double>(y); // error: no matching function for call to ‘foo(double&)’

return 0;
}

编辑:欢迎临时解释,但如果有人能指出具体的规范会更好。说。谢谢!

最佳答案

在第一个中,编译器知道 Aint因为你特意用 foo<int> 告诉它, 它知道 B也是int因为你传递给它的参数。所以两者都是AB是已知的或可以推导出来的(您可以说:A提供的B暗示的)。

但是,在第二个中,自 B先来 A没有出现在参数列表中,编译器无法判断是什么A是并给你一个错误。你明确地告诉它什么 Bfoo<int> 一起, 那么你传递的参数也是一个B在通话中,它是一个 int这与您之前对 B 的明确定义一致, 但没有提到 A ,隐式或显式,因此编译器必须停止并出错。

你真的不需要这个标准,这只是常识。到底会发生什么A在第二个?

谢谢你提出这个问题,因为我没有意识到你可以在这之前的参数列表中显式指定一些参数并隐式指定其他参数。

关于具有隐式参数的 C++ 函数模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323528/

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