接受所有类型作为函数中的参数 [英] Accept all types as argument in function
问题描述
我如何在 C++ 中使函数接受每个对象,以便我可以给它数字、字符串或其他对象.我在 C++ 方面不是很好,我希望这不是一个完全愚蠢的问题...
How can I in C++ make a function accept every Object, so I can give it numbers, String or other Objects. I am not very well in C++, I hope it's not a totally stupid question...
好的,举个例子:如果你想尝试将 std::cout 流包装到普通函数中,该函数应该能够接受一切——从浮点数上的整数到复杂的对象.我希望现在更清楚了!
Ok, an example: if you want to try to wrap the std::cout streams into normal functions, that funtion should be able to accept everything - from Integers over Floats to complex Objects. I hope it's more clear now!
推荐答案
您可以针对不同类型重载您的函数,即
You can overload your function for different types, i.e.
size_t func(int);
size_t func(std::string);
或者和/或另外,您可以提供一个函数模板,这是一种告诉编译器如何为任何特定类型生成函数的方法,例如
Alternatively and/or additionally, you can provide a function template, which is a way to tell the compiler how to generate your function for any particular type, for example
template<typename T>
size_t func(T const&) { return sizeof(T); }
您可以使用更高级的技术,例如 SFINAE 来有效地重载这些模板函数,即为不同类型的类型使用不同的模板 T
(即整数类型、指针、内置类型、pod, 等等).然后,编译器将为它遇到的任何函数调用选择最合适的 func()
(如果有),如果这是一个模板,则生成一个适当的函数.这不需要重新编码.
You may use more advanced techniques such as SFINAE to effectively overload those template functions, i.e. to use different templates for different kind of types T
(i.e. integral types, pointer, built-in types, pod, etc). The compiler will then pick the best-fitting func()
(if any) for any function call it encounters and, if this is a template, generate an appropriate function.
This requires no re-coding.
一种完全不同的方法是使用通用的擦除类型,例如boost::any
,当函数需要在编码时解析预期类型时(与编译时相反):
A completely different approach is to use a generic erasure type, such as boost::any
, when the function will need to resolve the expected types at coding-time (as opposed to compile-time):
size_t func(boost::any const&x)
{
auto i = boost::any_cast<const int*>(x);
if(i) return func(*i);
// etc for other types, but this must be done at coding time!
}
这篇关于接受所有类型作为函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!