c++ - C++ 中是否可以使用条件类型定义?

标签 c++ templates typedef typetraits

此题与c++有关

有一个库声明了一个名为 Solver < TS,FS > 的类。 Solver 是另一个类 Domain 的成员(我写的)

现在有很多域都有一个成员“int region”

我想做的是根据区域的值,我想让求解器接受 TS 和 FS 的不同参数。 我在想一些事情

template<int region>
struct Decider
{
  if(region==1)
  {
     typedef TSA TS;
     typedef FSA FS;
  }
  else
  if(region==2)
  {
     typedef TSB TS;
     typedef FSB FS;
  }
}

然后将其用作

Decider<region>::TS
Decider<region>::FS

但是,这里由于 if 的范围,我猜该结构是无用的。但是,我想不出更好的方法来做到这一点。有什么建议吗?

所有不同的 TS 和 FS 都有相同的接口(interface)。所以我不必担心内部代码。

最佳答案

您可以为任何 region 值专门化模板。

template<int region>
struct Decider;

template<>
struct Decider<1>
{
     typedef TSA TS;
     typedef FSA FS;
};

template<>
struct Decider<2>
{
     typedef TSB TS;
     typedef FSB FS;
};

关于c++ - C++ 中是否可以使用条件类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6348447/

相关文章:

c++ - 将 std::bind 转换为函数指针

c++ - C++ 中带位域的匿名 typedef 的前向声明

C++ 使用 typedef 避免类型转换警告

c++ - SWIG 无法正确转换 typedef 类型

c++ - 从 std::vector 中删除原始指针

C++ : cannot convert from 'char *' to 'char []' problem

c++ - 扩展 Eigen 库以包含排序

c++ - 将模板参数传递给线程中的模板函数

Django login_required 通过,但 user.is_authenticated 在模板中失败(??)

c++ - 错误: expected class-name before ‘{’ token with templates