【问题标题】:Conditional type conditioned by operating system受操作系统限制的条件类型
【发布时间】:2021-08-06 13:21:02
【问题描述】:

在这种情况下,您有什么建议避免使用类型别名?

// this is a header file, sample.h

#ifdef _WIN32
using default_type = int;
#else
using default_type = float;
#endif

template<typename T = default_type>
class Sample
{
};

我不想在这里使用类型别名,因为我不想在我的头文件中使用类型别名。

【问题讨论】:

  • 不想要别名的原因是什么?如果是名称冲突,命名空间可能是比解决方法更合适的解决方案。

标签: c++ templates using


【解决方案1】:

我不想在这里使用类型别名,因为我不想在我的头文件中使用类型别名。

由于您只提到您不想使用类型别名,因此我假设您对布尔常量一无所知:

// Works with only C++11 or above

#include <type_traits>

#ifdef _WIN32
constexpr auto is_win32 = true;
#else
constexpr auto is_win32 = false;
#endif

template<typename T = typename std::conditional<is_win32, int, float>::type>
class Sample
{
};

【讨论】:

  • constexpr?
  • @Bathsheba 对,我将使用constexpr,因为它更简洁。
【解决方案2】:

如果您绝对不想在标题中使用 typedef,您可以在模板声明中内联条件

template<typename T = 
#ifdef WIN32
int
#else
float
#endif
>
class Sample
{
    using value_type = T; // not necessary, but might be nice to have
};

使用类内value_type 定义,您可以引用默认类型,例如typename Sample&lt;&gt;::value_type

【讨论】:

  • 我喜欢这样,特别是如果你通过类内的using MyType = T; 之类的东西来激励你类的用户,以避免任何重复。
  • 标准喜欢在类中对模板参数进行typedef,所以最好有
【解决方案3】:
#ifdef WIN32
#define default_type int
#else
#define default_type flat
#endif

template<typename T = default_type>
class Sample:
{
};

#undef default_type

瞧:没有类型别名,没有名称泄漏。

【讨论】:

  • 为了更加严格,请检查 default_type 是否尚未定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多