0

こんにちは、作成した variadic add テンプレートで move ctor が呼び出されないという問題があります。

#include <iostream>
#include <algorithm>
#include <functional>

class wrapped_heap_integer{
public:
    wrapped_heap_integer() : value(nullptr)
    {
        std::cout << "Default ctor\n"; 
    }
    explicit wrapped_heap_integer(int value_) : value(new int(value_))
    {
        std::cout << "ctor\n";
    }
    ~wrapped_heap_integer(){
        if(value != nullptr) delete value;
        std::cout << "dtor\n"; 
    }
    wrapped_heap_integer(wrapped_heap_integer const & other) : value(new int(*(other.value))){
        std::cout << "copy ctor\n"; 
    }
    wrapped_heap_integer(wrapped_heap_integer&& other) : value(other.value){
        other.value = nullptr;
        std::cout << "move ctor\n"; 
    }
    wrapped_heap_integer& operator = (wrapped_heap_integer other){
        std::swap(value,other.value);
        std::cout << "copy assignment\n"; 
        return *this;
    }
    wrapped_heap_integer& operator = (wrapped_heap_integer&& other){
        delete value;
        value = other.value;
        other.value = nullptr;
        std::cout << "move assignment\n"; 
        return *this;
    }
    wrapped_heap_integer operator + (wrapped_heap_integer const & other){
        wrapped_heap_integer a(*value + *(other.value));
        return a;
    }
    wrapped_heap_integer& operator+=(wrapped_heap_integer const & other){
        *value += *(other.value);
        return *this;
    }

    friend std::ostream& operator << (std::ostream& o, wrapped_heap_integer& w);
private:
    int* value;

};

std::ostream& operator << (std::ostream& o, wrapped_heap_integer& w){
    o << *(w.value);
    return o;
}

template<typename Head>
Head&& add(Head&& head){
    return std::forward<Head>(head);
}

template<typename Head, typename... Tail>
auto add(Head&& head, Tail&&... tail) -> decltype(head + add(std::forward<Tail>(tail)...))
{
    return head + add(std::forward<Tail>(tail)...);
}


int main(int argc, const char * argv[])
{

    auto result = add(wrapped_heap_integer(4),wrapped_heap_integer(10),wrapped_heap_integer(1));

    std::cout << result << std::endl;

    return 0;
}
4

1 に答える 1

0

ここで普遍的な参照を得たと思います。右辺値のコピーを作成しないように引数を転送します。

template<typename Head>
Head add(Head&& head){
    return std::forward<Head>(head);
}
于 2013-01-08T12:28:42.283 に答える