【发布时间】:2016-08-20 01:40:27
【问题描述】:
我想知道这样的事情在 C++11 中是否可能,例如当你有以下情况时,将适当数量和类型的参数传递给函数:
template <typename R, typename ... Types>
constexpr std::integral_constant<unsigned, sizeof ...(Types)> getArgumentCount( R(*f)(Types ...))
{
return std::integral_constant<unsigned, sizeof ...(Types)>{};
}
void foo(std::string first, double second, std::string third);
void bar(std::string first, std::string second);
void baz(std::string first, int c);
void passArgs(std::vector<std::string> arguments)
{
//Get arguments count for function foo, do the same for the others
size_t foo_count = decltype(getArgumentCount(foo))::value;
//Here pass appropriate amount of arguments to foo,bar and baz and
//convert to appropriate type using for example std::stoi and
//std::stod when the argument is int or double
Magic(foo,arguments,foo_count);
}
int main()
{
}
提前谢谢你。
【问题讨论】:
-
您正在尝试做的事情非常复杂且有问题。如果可能的话,使用继承会更容易;具有可以使用的方法 numArgs() 和 argType( unsigned int index ) 的基类,然后在汇编中执行一些函数技巧(将 args 推入堆栈),或者创建一个模板派生类,然后向下转换为调用函数。
-
你怎么知道字符串
"3.54"是文本"3.54"还是double?只是假设任何可以是 int 的东西,如果是双精度数,则不是字符串?您可以使用boost::lexical_cast<>(或您自己的实现 - 使用istringstream占用约 5 行代码)进行转换。不过,您将需要在函数调用之间使用某种switch,或者可能是参数数量及其类型的数字编码,您可以将其传递给知道可用函数并让它选择匹配的模板参数列表。 -
@Tont D 你知道函数签名必须是什么类型,例如
foofirst必须是string,second是double和third是string。std::vector<std::string> arguments中的参数顺序正确。
标签: c++ c++11 templates c++14 metaprogramming