gpt4 book ai didi

c++ - 我想知道为什么模板方法可以调用非模板方法?

转载 作者:行者123 更新时间:2023-11-30 03:56:59 27 4
gpt4 key购买 nike

我是 C++ 模板的新手。如果我定义了一个模板方法,我发现我可以调用非模板方法

例如

void non_template(double x)
{
}

template<typename T>
void testClass<T>::method1() {
/*****/
T var1;
//call a nontemplate here using var1
non_template(var1);
}

我不确定为什么可以在没有任何编译错误的情况下允许这样做;如果我的var1是int,会不会出错?

最佳答案

I am not sure why this can be allowed without any compilation errors; If my var1 is int, will it be wrong?

模板类和函数的工作方式与非模板类和函数略有不同:有效性检查分两次完成 - 一次在定义时,另一次在实例化(首次调用方法时)时。

在处理模板函数时,它会检查诸如语法之类的内容,并且类型不依赖于模板参数。如果这些成功,它不会提示并将模板的定义存储在它的状态中。

当您尝试使用一组特定参数调用(实例化)模板时,它将返回到存储的定义并重新检查依赖于传入参数类型的内容。

因此,如果我尝试使用 int、double 和 float 来调用您的函数,例如:

 test_calls.method(5.0); // Works as expected
test_calls.method(5); // Works, because int can be converted to double implicitly.
test_calls.method("Hello"); // Doesn't work, because "non-templated" cannot be call with a char const* argument.

关于c++ - 我想知道为什么模板方法可以调用非模板方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250809/

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