首页 > 解决方案 > 如何就地从临时变量初始化非静态私有模板成员变量,即不进行复制或移动?

问题描述

我想从临时就地初始化类模板的两个非静态私有模板成员变量,即不进行复制或移动。

为澄清起见,请考虑以下示例代码:

#include <iostream>

struct P {
    P(int n) : n_ { n } {};

    P(P&&) { std::cout << "P:moved" << std::endl; }
    P(const P&) { std::cout << "P:copied" << std::endl; }

    int n_;
};

struct Q {
    Q(double x) : x_ { x } {};

    Q(Q&&) { std::cout << "Q:moved" << std::endl; }
    Q(const Q&) { std::cout << "Q:copied" << std::endl; }

    double x_;
};

/* note that P and Q are just two illustrative examples;
   don't count on anything specific in them; with respect
   to the asked question, they should just represent two
   arbitrary classes with arbitrary ctors */

template<typename U, typename V>
class X {
    public:
        X(U u, V v) : u_ { u }, v_ { v } {}

    private:
        U u_;
        V v_;
};

int
main(
) {
    X x { P { 0 }, Q { 0.0 } };

    return 0;
}

输出(使用 gcc 8.2.0)是P:copied Q:copied因为 u 和 v 分别复制到 X 的 ctor 中的 u_ 和 v_ 。但是,由于临时变量 P { 0 } 和 Q { 0.0 } 仅分别用于初始化 u_ 和 v_,我想知道是否可以就地初始化这两个成员变量。copied我既不想看,也不想moved在这里。更重要的是,我想在删除 P 和 Q 的复制和移动 ctor 的情况下运行此代码。

这在 C++17(或更早版本)中是否可行,如果可以,如何实现?

标签: c++c++11initializationc++17copy-elision

解决方案


基本上要做你想做的事,你需要构建一种接口,std::pair用于将成员的构造函数的参数转发给成员。他们这样做的方法是构建参数的元组,然后将这些元组委托给另一个构造函数,该构造函数也获取std::integer_sequence每个元组参数包的大小,因此它可以解包元组,使用这些序列直接调用成员构造函数。以下代码并不完美,但它会让您开始构建生产版本。

template<typename U, typename V>
class X {
    public:
        // old constructor that makes copies
        X(U u, V v) : u_ { u }, v_ { v } { std::cout << "X(U, V)\n"; }

        // this is the constructor the user code will call
        template<typename... Args1, typename... Args2>
        X(std::piecewise_construct_t pc, std::tuple<Args1...>&& u, std::tuple<Args2...>&& v) : 
            X(pc, std::move(u), std::move(v), std::make_index_sequence<sizeof...(Args1)>{}, std::make_index_sequence<sizeof...(Args2)>{}) {}

        // this is where the magic happens  Now that we have Seq1 and Seq2 we can
        // unpack the tuples into the constructor
        template<typename... Args1, typename... Args2, auto... Seq1, auto... Seq2>
        X(std::piecewise_construct_t pc, std::tuple<Args1...>&& u, std::tuple<Args2...>&& v, std::integer_sequence<size_t, Seq1...>, std::integer_sequence<size_t, Seq2...>) : 
            u_ { std::get<Seq1>(u)... }, v_ { std::get<Seq2>(v)... } {}

    private:
        U u_;
        V v_;
};

int main() 
{
    // and now we build an `X` by saying we want the tuple overload and building the tuples
    X<P,Q> x { std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple(0.0) };
    // Unfortunetly we don't get CTAD with this.  Not sure if that can be fixed with a deduction guide
}

您还可以查看诸如 libc++ 或 libstdc++ 之类的开源 C++ 库之一,以了解它们如何实现std::pair的分段构造函数以了解如何使其具有生产价值。


推荐阅读