接受所有类型作为函数中的参数 [英] 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);
或者和/或另外,您可以提供函数 template ,这是一种告诉编译器如何为任何特定类型生成函数的方法,例如
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屋!