【发布时间】:2017-04-27 11:42:30
【问题描述】:
尽管模板类型在运行时被解析,但我试图理解为什么以下编译/运行。是不是因为单独对f 的if/else 调用就足以告诉编译器创建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的值运行相应的分支。
标签: c++ function templates runtime compile-time