【问题标题】:Google Test and boost::variant谷歌测试和提升::变体
【发布时间】:2012-10-30 15:13:58
【问题描述】:

我希望在我的单元测试中迭代我的 boost::variant 中的类型。这可以按如下方式完成:

TEST_F (MyTest, testExucutedForIntsOnly)
{
    typedef boost::variant<int, char, bool, double> var;
    boost::mpl::for_each<SyntaxTree::Command::types>(function());
    ...
}

其中函数是函子。我只是想确保变体中的一种类型相对于所有其他类型的特定操作发生不同。但是,我不喜欢现在在另一个函数中完成测试——如果我希望从函子访问 MyTest 的成员怎么办?看起来真的很乱。

对更好的方法有什么建议吗?

【问题讨论】:

  • 我需要兼容c++98

标签: boost googletest c++98


【解决方案1】:

那么,你想在 boost::variant 上调用一个依赖于类型的函数吗?

试试这个:

template<typename T>
struct RunOnlyOnType_Helper
{
  std::function<void(T)> func;
  template<typename U>
  void operator()( U unused ) {}
  void operator()( T t ) { func(t); }
  RunOnlyOnType_Helper(std::function<void(T)> func_):func(func_){}
};

template<typename T, typename Variant>
void RunOnlyOnType( Variant v, std::function< void(T) > func )
{
  boost::apply_visitor( RunOnlyOnType_Helper<T>(func), v );
}

这个想法是 RunOnlyOnType 是一个函数,它从变体中获取一个变体和一个特定类型的函子,当且仅当变体的类型与函子匹配时才执行函子。

那么你可以这样做:

typedef boost::variant<int, char, bool, double> var;
var v(int(7)); // create a variant which is an int that has value 7
std::string bob = "you fool!\n";
RunOnlyOnType<int>( v, [&](int value)->void
{
  // code goes here, and it can see variables from enclosing scope
  // the value of v as an int is passed in as the argument value
  std::cout << "V is an int with value " << value << " and bob says " << bob;
});

这是你想要的吗?

免责声明:我之前从未接触过boost::variant,以上内容尚未编译,这是基于快速阅读 boost 文档。此外,上面使用std::function 是次优的(您应该能够一直使用模板化函子——哎呀,您可能可以从函子的类型签名中提取类型 T)。

【讨论】:

  • 我需要兼容 C++98,所以我不能使用 lambdas :(
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 2013-07-13
  • 2012-08-17
  • 2014-04-04
  • 2011-04-02
相关资源
最近更新 更多