模板类方法的默认参数

发布于 2024-12-06 04:20:38 字数 300 浏览 3 评论 0原文

有没有办法为模板类的方法提供默认参数值?例如,我有以下内容:

template<class T>
class A
{
public:
    A foo(T t);
};

我应该如何修改它以给 foo 类型为 T 的默认参数?例如:Tint,则默认值为 -23,或者 Tchar*,则默认值“某物”等。这可能吗?

Is there a way to provide default parameter values for methods of a template class? For example I have the following:

template<class T>
class A
{
public:
    A foo(T t);
};

How should I modify this to give foo a default parameter of type T? For example: T is int then a default value of -23, or T is char* then default value of "something", etc. Is this even possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随遇而安 2024-12-13 04:20:38

如果您希望默认参数只是默认值(通常为零),那么您可以编写 A foo(T t = T())。否则,我建议使用特征类:

template <typename T> struct MyDefaults
{
  static const T value = T();
};

template <> struct MyDefaults<int>
{
  static const int value = -23;
};


template<class T>
class A
{
public:
    A foo(T t = MyDefaults<T>::value);
};

我相信,在类定义内部编写常量值仅适用于整数类型,因此您可能必须在所有其他类型的外部编写它:

template <> struct MyDefaults<double>
{
  static const double value;
};
const double MyDefaults<double>::value = -1.5;

template <> struct MyDefaults<const char *>
{
  static const char * const value;
};
const char * const MyDefaults<const char *>::value = "Hello World";

在 C++11 中,您也可以说 static constexpr T value = T(); 使模板适用于非整数值,前提是 T 有一个声明为 constexpr 的默认构造函数:

template <typename T> struct MyDefaults
{
  static constexpr T value = T();
};

template <> struct MyDefaults<const char *>
{
  static constexpr const char * value = "Hello World";
};

If you want the default parameter to be just the default value (zero, usually), then you can write A foo(T t = T()). Otherwise, I suggest a trait class:

template <typename T> struct MyDefaults
{
  static const T value = T();
};

template <> struct MyDefaults<int>
{
  static const int value = -23;
};


template<class T>
class A
{
public:
    A foo(T t = MyDefaults<T>::value);
};

Writing the constant value inside the class definition only works for integral types, I believe, so you may have to write it outside for all other types:

template <> struct MyDefaults<double>
{
  static const double value;
};
const double MyDefaults<double>::value = -1.5;

template <> struct MyDefaults<const char *>
{
  static const char * const value;
};
const char * const MyDefaults<const char *>::value = "Hello World";

In C++11, you could alternatively say static constexpr T value = T(); to make the template work for non-integral values, provided that T has a default constructor that is declared constexpr:

template <typename T> struct MyDefaults
{
  static constexpr T value = T();
};

template <> struct MyDefaults<const char *>
{
  static constexpr const char * value = "Hello World";
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文