sbi*_*sbi 5 c++ templates template-meta-programming variadic-templates c++14
在现代 C++(GCC 5.1.0,所以 C++14,我猜)中,在编译时传递 an 值列表,enum然后在运行时检查哪些值在中的最快方法是什么?那里?
enum foobar { foo, bar, baz };
template<????>
void f() {
if( contains<????, foo>() )
std::cout << "foo!";
if( contains<????, bar>() )
std::cout << "bar!";
if( contains<????, baz>() )
std::cout << "baz!";
}
f<foo,bar>();
Run Code Online (Sandbox Code Playgroud)
注意:这是针对单元测试的,因此速度等主要无关紧要,主要目标是让不熟悉代码的人能够解读它。
这是一项建议
#include <initializer_list>// pulled in by a lot of stuff
enum class options { foo,bar,baz };
void test_func(options opt)
{
}
int main()
{
auto test_vector = { options::foo, options::bar };
for (auto option : test_vector)
{
test_func(option);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
检查提供的测试向量是否包含应包含的内容稍微复杂一些:
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
enum class options { foo, bar, baz, wuz };
void test_func(options)
{
}
template<typename AT, typename BT>
void assert_test_vectors(AT a, BT check_these_items)
{
for (auto item : check_these_items)
{
auto test = std::find(a.begin(), a.end(), item) != a.end();
if (!test)
{
return throw std::runtime_error("You suck");
}
}
}
template<typename T>
void run_tests(T tests)
{
const auto better_have_these = { options::foo, options::bar };
assert_test_vectors(tests, better_have_these);
for (auto test : tests)
{
test_func(test);
}
}
int main()
{
const auto test_vectors = { options::foo, options::wuz };
run_tests(test_vectors);
return 0;
}
Run Code Online (Sandbox Code Playgroud)