我想了解为什么以下编译/运行尽管在运行时解析模板类型。是否因为单独调用来调用f
就足以告诉编译器创建void f<double>(double)
和void f<std::string>(std::string)
?在运行时功能模板类型扣除
test.hpp
#include <type_traits>
#include <string>
#include <iostream>
template <typename T>
void f(T x) {
if(std::is_same<T, std::string>::value)
std::cout << "String: " << x;
}
TEST.CPP
#include <iostream>
#include "test.hpp"
int main(int, char** argv) {
double x(std::stod(argv[1]));
if(x < 42) f(x);
else f(std::to_string(x));
return 0;
}
$ (clan)g++ -std=c++14 test.cpp
$ ./a.exe 41
$ ./a.exe 43
String: 43.000000
为if和else分支生成代码。在运行时,根据'x'的值运行相应的分支。 –