c++ - 是否可以根据 C++ 中的输入变量定义不同类型的变量?

标签 c++ runtime

我正在开发一种算法,我需要根据输入变量将一个 vector 定义为实数或复数。伪像

void foo(bool is_real)
{
  if (is_real)
  {
    vector< double > v; 
  }
  else vector< complex > v;
}

现在我正在编写两个不同版本的算法,如果 is_real 为真,我将使用真实案例的算法,否则,使用复杂案例。实际上,除了数据类型之外,这两种算法完全相同。所以我用谷歌搜索了一下

#if is_real
  vector< double > v;
#else
  vector< complex > v;
#endif

但是这段代码无法编译。我正在使用 linux gnu c++ 4.7.2。我想知道宏是否仅适用于 Microsoft C++?我觉得不舒服,因为在我的实现中唯一的区别是数据类型,有什么方法可以选择在运行时应该使用什么类型?谢谢。

最佳答案

如果代码完全相同,则将其设为模板:

namespace detail {
    template <typename T>
    void foo() {
        vector<T> v;
        // blah
    }
}

void foo(bool is_real)
{
  if (is_real)
  {
    detail::foo<double>();
  }
  else detail::foo<complex>();
}

关于c++ - 是否可以根据 C++ 中的输入变量定义不同类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053667/

相关文章:

c++ - 链接 : fatal error LNK1104: cannot open file 'msmpi.lib' visual studio 2010

windows - D 运行时作为 DLL

c# - 将 SetTimer() 和 KillTimer() 移植到 C#?

c++ - 除以 1000 对 double var 进行四舍五入并失去小数位

algorithm - 采访 : Renaming all files in a directory using a data structure

delphi - Firemonkey 中缺少事件操作和过程

python - 让尝试更快地捕捉 Python

cocoa - 从 cocoa 代码中获取链接库列表

c++ - 显示函数的枚举值

c++ - 如何在linux/c++中控制主音量?