【发布时间】:2021-04-14 10:19:28
【问题描述】:
我正在编写一个 C++ 网络库,并希望主(模板)函数以随机顺序接受参数,使其更加用户友好,就像 CPR 库一样.
模板函数最多可以同时接受 10 个参数,每个参数都有不同的类型。有没有办法实例化模板以接受任何随机顺序的参数类型,而不是必须手动包含每种可能性的代码?
例如 - 在这种情况下使用 3 个参数,每个参数都有不同的类型:
.h 文件
namespace foo
{
template <typename T, typename U, typename V> void do(const T& param_a, const U& param_b , const V& param_c);
};
.cpp 文件
template <typename T, typename U, typename V>
void foo::do(const T& param_a, const U& param_b, const V& param_c) {
//do lots of stuff
}
//instantiate to allow random param order
template void foo::do<int, std::string, long>(const int&, const std::string&, const long&);
template void foo::do<int, long, std::string>(const int&, const long&, const std::string&);
template void foo::do<int, std::string, int>(const int&, const std::string&, const int&);
//etc... to cover all possible param orders
【问题讨论】:
-
string与string有何不同?请参阅第二次实例化。 -
您可能对how-to-generate-all-the-permutations-of-function-overloads 感兴趣(实际上是 C++14,但可能在 C++11 中完成)。
-
@zdf 我的错,把它改成不同的类型
-
@Yksisarvinen 它是一个库,我需要实例化以便应用程序链接
-
顺便说一句,您不需要在
<>中指定模板参数,因为有可推导。