运行时的函数模板类型推导 您所在的位置:网站首页 c模板函数写法 运行时的函数模板类型推导

运行时的函数模板类型推导

#运行时的函数模板类型推导| 来源: 网络整理| 查看: 265

if(x

编译器在编译时知道它x是一个双精度因此它会被标记出来

void f(double)

然后进去

else f(std::to_string(x));

编译器知道返回类型std::to_string是一个,std::string所以它标记了一个

void f(std::string)

使用.这两个函数同时存在,并且在运行时只调用一个函数,具体取决于您为程序提供的输入.

让我们看看chris在他的评论中提供的这个示例代码.运用

#include template __attribute__((used)) int f(T x) { if(std::is_same::value) return 1; else return 2; } int main(int argc, char** argv) { if(argc > 1) return f(1); else return f(1.0); }

编译时会-O3 -std=c++1z -Wall -Wextra -pedantic生成程序集

main: # @main xor eax, eax cmp edi, 2 setl al inc eax ret int f(int): # @int f(int) mov eax, 1 ret int f(double): # @int f(double) mov eax, 2 ret

正如您所看到的那样,程序集中存在两个模板函数,并且它只是if在main中决定在运行时调用哪个函数.

1> NathanOliver..:

这里没有运行时模板扣除.当你有

if(x

编译器在编译时知道它x是一个双精度因此它会被标记出来

void f(double)

然后进去

else f(std::to_string(x));

编译器知道返回类型std::to_string是一个,std::string所以它标记了一个

void f(std::string)

使用.这两个函数同时存在,并且在运行时只调用一个函数,具体取决于您为程序提供的输入.

让我们看看chris在他的评论中提供的这个示例代码.运用

#include template __attribute__((used)) int f(T x) { if(std::is_same::value) return 1; else return 2; } int main(int argc, char** argv) { if(argc > 1) return f(1); else return f(1.0); }

编译时会-O3 -std=c++1z -Wall -Wextra -pedantic生成程序集

main: # @main xor eax, eax cmp edi, 2 setl al inc eax ret int f(int): # @int f(int) mov eax, 1 ret int f(double): # @int f(double) mov eax, 2 ret

正如您所看到的那样,程序集中存在两个模板函数,并且它只是if在main中决定在运行时调用哪个函数.

为了便于说明,您可以查看一个示例的程序集,其中没有""和""的膨胀:https://godbolt.org/g/p2oF34


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有