假設我有一些類似(重復的)代碼,我想使用模板重構:
#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某種方式傳遞行中的默認引數。有沒有更好的辦法?
uj5u.com熱心網友回復:
您可以使用引數包來指定默認引數,例如
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
居住
BTW:請注意,float在 C 20 之前不能用作非型別模板引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/452379.html
