ove*_*nge 3 c++ templates auto c++14
考虑一下代码,
#include <cstdio>
auto f(const auto &loc){
printf("Location: %p\n", &loc);
}
int main()
{
auto x {1};
auto y {2.3};
f(x);
f(y);
}
Run Code Online (Sandbox Code Playgroud)
编译 g++ -std=c++14 dummy.cpp
题:
对于模板函数,f<int>(2)在编译时明确提到类型().
函数如何f接受不同类型的参数?
根据概念技术规范,'功能'
auto f(const auto &loc){
printf("Location: %p\n", &loc);
}
Run Code Online (Sandbox Code Playgroud)
实际上是一个template(缩写的函数模板声明),相当于(但更短,更容易阅读)
template<typename T>
void f(const T&loc){
printf("Location: %p\n", &loc);
}
Run Code Online (Sandbox Code Playgroud)
但是请注意,使用的表单auto不是任何C++标准的一部分,而只是概念和约束的概念技术规范,它看起来非常强大(但AFAIK只有GNU的gcc版本≥6.1支持选项-fconcepts) .