我想了解爲什麼以下編譯/運行儘管在運行時解析模板類型。是否因爲單獨調用來調用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'的值運行相應的分支。 –