gpt4 book ai didi

c++ - 为不同版本的函数模板识别不同的默认参数

转载 作者:行者123 更新时间:2023-11-28 01:28:13 24 4
gpt4 key购买 nike

首先我有一个函数模板

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它叫。 请注意 ba之后在 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也不推荐,因为它可能会导致 future 的标准添加与您自己的代码之间发生冲突。

解决您的问题的一种方法是将您的默认参数移动到具有特化的模板类:

#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更改默认参数则不再需要函数重载。

关于c++ - 为不同版本的函数模板识别不同的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52848603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com