C++ 将变量类型传递给函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22127041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ pass variable type to function
提问by user3325976
How can I pass a variable type to a function? like this:
如何将变量类型传递给函数?像这样:
void foo(type){
cout << sizeof(type);
}
回答by Joseph Mansfield
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);
}
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.
例如,您可以使用foo<int>()
. 它将实例化函数的一个版本,T
替换为int
. 查找函数模板。
回答by microtherion
As Joseph Mansfield pointed out, a function template will do what you want. In some situations, it may make sense to add a parameter to the function so you don't have to explicitly specify the template argument:
正如 Joseph Mansfield 指出的那样,函数模板可以满足您的需求。在某些情况下,向函数添加参数可能是有意义的,这样您就不必显式指定模板参数:
template <typename T>
void foo(T) {
cout << sizeof(T)
}
That allows you to call the function as foo(x)
, where x
is a variable of type T. The parameterless version would have to be called as foo<T>()
.
这允许您将函数调用为foo(x)
,其中x
是 T 类型的变量。无参数版本必须调用为foo<T>()
。