假设我有一段(重复的)代码,我想使用模板进行重构:
#include <iostream>
#include <algorithm>
#include <set>
struct IntFoo {
auto f(int arg, std::set<int> s = {1, 2, 3}) {
return std::find(s.begin(), s.end(), arg) != s.end();
}
};
struct FloatFoo {
auto f(float arg, std::set<float> s = {4.0f, 5.0f, 6.0f}) {
return std::find(s.begin(), s.end(), arg) != s.end();
}
};
int main() {
std::cout << IntFoo().f(3) << std::endl;
std::cout << FloatFoo().f(4.0f) << std::endl;
}
如您所见,除了类型差异之外,f()
的第二个参数的默认参数也发生了变化。
我能想到的最好的办法是:
#include <iostream>
#include <algorithm>
#include <set>
template<typename T, typename Def>
struct Foo {
auto f(T arg, std::set<T> s = Def::defaults){
return std::find(s.begin(), s.end(), arg) != s.end();
}
};
struct FooIntDefaults {
static constexpr std::initializer_list<int> defaults{1, 2, 3};
};
struct FooFloatDefaults {
static constexpr std::initializer_list<float> defaults{4.0f, 5.0f, 6.0f};
};
using IntFoo = Foo<int, FooIntDefaults>;
using FloatFoo = Foo<float, FooFloatDefaults>;
这可行,但有点冗长。我不太喜欢这些辅助结构。
理想情况下,我想以某种方式在 using
行中传递默认参数。有更好的办法吗?
最佳答案
您可以使用parameter pack用于指定默认参数,例如
template<typename T, T... defaults>
struct Foo {
auto f(T arg, std::set<T> s = {defaults...}){
return std::find(s.begin(), s.end(), arg) != s.end();
}
};
using IntFoo = Foo<int, 1, 2, 3>; // specify default arguments when defining type
using FloatFoo = Foo<float, 4.0f, 5.0f, 6.0f>; // specify default arguments when defining type
顺便说一句:请注意,在 C++20 之前,float
不能用作非类型模板参数。
关于c++ - 模板类成员函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71675005/