简体   繁体   中英

Disable Copy constructor of template class

How can I disable the copy constructor of a template class.

Eg:

template<typename T>
struct X {
    T property;
    constexpr X(const T property): property(property) { }

    friend std::ostream& operator<<(std::ostream& out, const X& x) {
        return out << "{ " << x.property << " }";
    }
};

The Problem:

If I let the class contain itself

constexpr X x1 { 1 };
std::cout << x1 << "\n"; // prints "{ 1 }"
constexpr X x2 { x1 };
std::cout << x2 << "\n"; // prints "{ 1 }", expected "{ { 1 } }"

My Hypothesis is that the copy constructor is called. Deleting the copy constructor does not help. Then I get a compile time error.

You can use a template helper function

template<typename T>
X<T> helper(const T& x) {
    return x;  // This will invoke the construtor
}

then when using

helper(x1);

the type T will be correctly found to be X<int> .

OK I have found a nicer solution for C++17 thanks to Ben Voigt.

template<typename T>
struct X {
    T property;
    constexpr X(const T property): property(property) { }

    friend std::ostream& operator<<(std::ostream& out, const X& x) {
        return out << "{ " << x.property << " }";
    }
};

You need to add a deduction guide:

template<typename T>
X(X<T>) -> X<X<T>>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM