具有移动语义的C ++可变参数模板函数

问题描述 投票:1回答:3

在C ++中,我有一组可变参数模板函数,我想接受任意数量的参数,这些参数可以是常量引用,也可以作为r值引用(因此,我可以移动而不是复制)。但是,我发现即使在std::move()中包装参数时,也会调用接受常量引用的版本。

// Accept end of parameters.
void example () {}

// Accept a non-constant R-value reference to do a move
template <typename... More>
void example (std::string &&value, More... parameters) {
    std::cout << value << ": moved" << std::endl;
    example (parameters...);
}

// Accept a constant reference parameter.    
template <typename... More>
void example (const std::string &value, More... parameters) {
    std::cout << value << ": copied" << std::endl;
    example (parameters...);
}

int main (int, char **) {
    std::string first { "first" };
    std::string second { "second" };
    std::string third { "third" };

    std::cout << "Trying variadic with move as second parameter: " << std::endl;
    example (first, std::move (second), third);
    // std::cout << "Trying variadic with move as first parameter: " << std::endl;
    // This next line won't even compile when uncommented
    // example (std::move (first), std::move (second), third);
    return 0;
}

输出为:

Trying variadic with move as second parameter: 
first: copied
second: copied
third: copied

而不是预期的:

Trying variadic with move as second parameter: 
first: copied
second: moved
third: copied

另外,当我将第一个参数包装在std::move()中时,在g ++ 7和clang 9上都出现编译错误。

我在做什么错?

在C ++中,我有一组可变参数模板函数,我想接受任意数量的参数,这些参数可以是常量引用,也可以作为r值引用(因此,我可以移动东西,而不是...

c++ variadic-templates
3个回答
1
投票

这里有几个问题:


0
投票

此作品:


0
投票

[HolyBlackCat已经提到了为什么您的代码会如此运行,所以在这里我不再赘述。这是使用折叠表达式的另一种解决方案:

© www.soinside.com 2019 - 2024. All rights reserved.