首先我有一个函数模板
template<typename S>
void foo(const S & s, int a = 1, double b = 2)
然后我想提供给定的专门实现S
是一个 STL 容器。特别是,我想提供不同的默认参数。
由于在 C++ 中不允许部分函数模板特化,我只是重载foo
. 说
template<typename T>
void foo(const vector<T> & s, int a = 3, double b = 4)
在这一点上一切都很好。
现在我想写一个函数模板partial_foo
,它只接受一个参数double b = 6
,然后让编译器a
根据foo
它调用的版本决定默认参数。请注意,b
是后a
在的调用签名foo
。
template<typename S>
foo_partial(const S & s, double b = 6)
理想情况下,foo_partial(int)
会有一个默认参数,int a = 1
而foo_partial(vector<int>())
会有一个默认参数int a = 3
。
我的问题是:foo_partial
鉴于foo
?的设计,我可以这样做(即如何实现),或者是否有任何解决方法?
对于一个具体的例子,请考虑
#include <bits/stdc++.h>
using namespace std;
template<typename S>
void foo(const S & s, int a = 1, double b = 2)
{
printf("foo(S) with a = %d, b = %.0f\n", a, b);
}
template<typename T>
void foo(const vector<T> & t, int a = 3, double b = 4)
{
printf("foo(vector<T>) with a = %d, b = %.0f\n", a, b);
}
template<typename S>
void foo_partial(const S & s, double b = 6)
{
// how to implement foo_partial so that ____ corresponds to
// the default argument in the proper version of foo?
int ____ = 5;
foo(s, ____, b);
}
int main()
{
foo_partial(0);
foo_partial(vector<int>());
}
输出是
foo(S) with a = 5, b = 6
foo(vector<T>) with a = 5, b = 6
我的问题相当于:有什么我可以用设计做的事情或任何解决方法,foo_partial
以便输出
foo(vector) with a = 1, b = 6
foo(forward_list) with a = 3, b = 6
感谢您的时间!
不要包含#include <bits/stdc++.h>
它是非标准的并且在大多数平台上都不起作用。
using namespace std
也不推荐,因为它可能会导致未来的标准添加和您自己的代码之间发生冲突。
解决您的问题的一种方法是将您的默认参数移动到具有专业化的模板类:
#include <vector>
#include <cstdio>
using std::vector;
template <typename S>
struct defaults
{
static constexpr int a = 1;
static constexpr double b = 2;
};
template <typename T>
struct defaults<vector<T>>
{
static constexpr int a = 3;
static constexpr double b = 4;
};
template<typename S>
void foo(const S & s, int a = defaults<S>::a, double b = defaults<S>::b)
{
printf("foo(S) with a = %d, b = %.0f\n", a, b);
}
template<typename T>
void foo(const vector<T> & t, int a = defaults<vector<T>>::a, double b = defaults<vector<T>>::b)
{
printf("foo(vector<T>) with a = %d, b = %.0f\n", a, b);
}
template<typename S>
void foo_partial(const S & s, double b = 6)
{
foo(s, defaults<S>::a, b);
}
int main()
{
foo_partial(0);
foo_partial(vector<int>());
}
如果您只是专门foo
更改默认参数,则不再需要函数重载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句