作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!