c++ - 模板类成员函数的默认参数

标签 c++ c++11 templates default-arguments

假设我有一段(重复的)代码,我想使用模板进行重构:

#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

LIVE

顺便说一句:请注意,在 C++20 之前,float 不能用作非类型模板参数。

关于c++ - 模板类成员函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71675005/

相关文章:

c++ - 模板实例化困惑

c++ - 为什么 C++ 允许但忽略将 const 应用于函数类型?

c++ - 开始 Direct3D,简单三角形不渲染

c++ - 我可以禁止在对象实例上调用静态方法吗?

c++ - 将共享指针添加到 vector 时出错

c++ - SFINAE 显式工作但不隐式工作

c++ - 插入 map 时多次调用析构函数

c++ - 带有 std::all_of( ) 和 std:none_of( ) 的空容器的好用法?

c++ - 在 C++ 中使用数组创建哈希表表示

java - 你如何在 Play Framework scala 模板中使用 DTO?