Reputation: 2749
How can I disable the copy constructor of a template class.
E.g.:
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.
Upvotes: 0
Views: 235
Reputation: 2749
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>>;
Upvotes: 0
Reputation: 114559
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>
.
Upvotes: 1