CppQuiz系列 1

来源:互联网 发布:淘宝 css 显示代码 编辑:程序博客网 时间:2024/06/03 16:43

本系列是CppQuiz 的题解的中文翻译,在被虐无数次后终于通关,CppQuiz主要关注c++11中容易出错的一些点,比较坑,也比较烧脑。

keywords : 模板,参数匹配

#include <iostream>template <class T> void f(T &i) { std::cout << 1; }template <> void f(const int &i) { std::cout << 2; }int main() {  int i = 42;  f(i);}

模板实例化时会实例化为void f(int &),和特化的模板void f(const int &)更为匹配,如果改成const int i=42;就会输出2。

The templated function will be instantiated as void f(int&), which is a better match than f(const int&).

好,问题来了,改成f(42)会发生什么?

答案是:CE(compilation error),至于为什么,将在下一期解析。

0 0
原创粉丝点击