未命名的功能参数

Syn*_*ose 1 c++ c++11 hpx

我正在查看一些与n3960标准提案有关的代码,并注意到一些函数具有没有名称的参数,但具有完整的函数定义.有人可以解释这是怎么回事吗?

例:

template <typename ExPolicy, typename IteratorTag>
void test_for_each(ExPolicy const& policy, IteratorTag) //just IteratorTag, no name?
{
    BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value);

    typedef std::vector<std::size_t>::iterator base_iterator;
    typedef test::test_iterator<base_iterator, IteratorTag> iterator;

    std::vector<std::size_t> c(10000);
    std::iota(boost::begin(c), boost::end(c), std::rand());

    hpx::parallel::for_each(policy,
        iterator(boost::begin(c)), iterator(boost::end(c)),
        [](std::size_t& v) {
            v = 42;
        });

    // verify values
    std::size_t count = 0;
    std::for_each(boost::begin(c), boost::end(c),
        [](std::size_t v) {
            HPX_TEST_EQ(v, std::size_t(42));
            ++count;
        });
    HPX_TEST_EQ(count, c.size());
}
Run Code Online (Sandbox Code Playgroud)

Yak*_*ont 6

如上所述,参数名称是可选的.但是为什么这个被省略了,为什么有一个没有名字的争论呢?

这里使用的技术是基于参数类型的函数模板标签类型推导.

您可以test_for_each在任意类型的实例中调用传递作为第二个参数.无论该参数的值类型最终被传递给template函数IteratorTag.

在类中,IteratorTag不使用变量的值- 我们关心的只是类型.

IteratorTags用于区分各种std库迭代器 - 转发,随机访问,输入,输出等.

有了这种类型,我们可以对代码的行为方式进行细微的更改(或者使用重载进行微妙的更改).在这种情况下,iterator函数中的IteratorTag类型将类型作为其template参数之一,因此该变量的类型根据IteratorTag传入而不同.

这是一个简单的版本,使用标签称为"标签调度":

template<typename T>
int floor_to_int( T&& t, std::true_type ) { return std::forward<T>(t); }
template<typename T>
int floor_to_int( T&& t, std::false_type ) { return floor(std::forward<T>(t)); }
template<typename T>
int smart_floor( T&& t ) {
  return floor_to_int( std::forward<T>(t), std::is_integral< typename std::decay<T>::type >{} );
}
Run Code Online (Sandbox Code Playgroud)

这里smart_floor函数采用任意类型T,当且仅当它是非整数类型时才调用floor它.否则,它只是将其转换为int.

我们创建了一个标签类型的实例 - 在这种情况下,std::is_integral< typename std::decay<T>::type >- 并将其传递给内部辅助函数.在这种情况下,我们有两个重载,它们都不使用传入标记的值,只使用其类型.

上述实现类似,但两种情况都有1次重载.也许这种标签类型将以类似的重载方式更深入地使用,或者它可能在一些更深层次的使用中专门用于某些特征类.

赔率是这里应该是std::iterator_traits< T >::iterator_category或一些自制boost变体的论点,作为旁白.

  • 你快速输入了这个!+1 (2认同)