将适当数量和类型的参数传递给函数
Pass appropriate amount and type of arguments to a function
我想知道在 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()
{
}
提前谢谢你。
#include <type_traits>
#include <utility>
#include <string>
#include <cstddef>
#include <vector>
template <typename T>
T convert(const std::string&);
template <>
int convert<int>(const std::string& s)
{
return std::stoi(s);
}
template <>
std::string convert<std::string>(const std::string& s)
{
return s;
}
template <>
double convert<double>(const std::string& s)
{
return std::stod(s);
}
template <typename R, typename... Args, std::size_t... Is>
void Magic(const std::vector<std::string>& arguments, R(*f)(Args...), std::index_sequence<Is...>)
{
f(convert<typename std::decay<Args>::type>(arguments[Is])...);
}
template <typename R, typename... Args>
void passArgs(const std::vector<std::string>& arguments, R(*f)(Args...))
{
Magic(arguments, f, std::make_index_sequence<sizeof...(Args)>{});
}
测试:
int main()
{
std::vector<std::string> arguments{"abc", "3.14", "def"};
passArgs(arguments, &foo);
passArgs(arguments, &bar);
passArgs(arguments, &baz);
}
演示
对于符合 C++11 的实现,您可以使用 index_sequence
的打击实现:
template <std::size_t...> struct index_sequence {};
template <std::size_t N, std::size_t... Is> struct make_index_sequence : make_index_sequence<N-1, N-1, Is...> {};
template <std::size_t... Is> struct make_index_sequence<0, Is...> : index_sequence<Is...> {};
演示 2
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数