C ++将变量类型传递给函数 [英] C++ pass variable type to function

查看:66
本文介绍了C ++将变量类型传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将变量类型传递给函数?像这样:

How can I pass a variable type to a function? like this:

void foo(type){
    cout << sizeof(type);
}

推荐答案

您不能传递这样的类型,因为类型不是对象.它们在运行时不存在.相反,您需要一个模板,该模板允许您在编译时实例化具有不同类型的函数:

You can't pass types like that because types are not objects. They do not exist at run time. Instead, you want a template, which allows you to instantiate functions with different types at compile time:

template <typename T>
void foo() {
  cout << sizeof(T);
}

您可以使用例如 foo< int>()调用此函数.它将实例化版本为 T 并替换为 int 的函数的版本.查找功能模板.

You could call this function with, for example, foo<int>(). It would instantiate a version of the function with T replaced with int. Look up function templates.

这篇关于C ++将变量类型传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆