Is there any way to create a type A
such that:
Given:
A f(...);
Then:
Both auto&& a = f(...);
and const auto& a = f(...);
give a compile errors?
The reason for this is that in this case, A
is an expression template which contains references to temporaries (that are provided as arguments to f
), so I don't want the lifetime of this object extended beyond the current expression.
Note I can prevent auto a = f(...);
from being an issue just by making A
s copy constructor private, and making f(...)
a friend of A if required.
Example of code (ideone link):
#include <iostream>
#include <array>
template <class T, std::size_t N>
class AddMathVectors;
template <class T, std::size_t N>
class MathVector
{
public:
MathVector() {}
MathVector(const MathVector& x)
{
std::cout << "Copying" << std::endl;
for (std::size_t i = 0; i != N; ++i)
{
data[i] = x.data[i];
}
}
T& operator[](std::size_t i) { return data[i]; }
const T& operator[](std::size_t i) const { return data[i]; }
private:
std::array<T, N> data;
};
template <class T, std::size_t N>
class AddMathVectors
{
public:
AddMathVectors(const MathVector<T,N>& v1, const MathVector<T,N>& v2) : v1(v1), v2(v2) {}
operator MathVector<T,N>()
{
MathVector<T, N> result;
for (std::size_t i = 0; i != N; ++i)
{
result[i] = v1[i];
result[i] += v2[i];
}
return result;
}
private:
const MathVector<T,N>& v1;
const MathVector<T,N>& v2;
};
template <class T, std::size_t N>
AddMathVectors<T,N> operator+(const MathVector<T,N>& v1, const MathVector<T,N>& v2)
{
return AddMathVectors<T,N>(v1, v2);
}
template <class T, std::size_t N>
MathVector<T, N> ints()
{
MathVector<T, N> result;
for (std::size_t i = 0; i != N; ++i)
{
result[i] = i;
}
return result;
}
template <class T, std::size_t N>
MathVector<T, N> squares()
{
MathVector<T, N> result;
for (std::size_t i = 0; i != N; ++i)
{
result[i] = i * i;
}
return result;
}
int main()
{
// OK, notice no copies also!
MathVector<int, 100> x1 = ints<int, 100>() + squares<int, 100>();
// Should be invalid, ref to temp in returned object
auto&& x2 = ints<int, 100>() + squares<int, 100>();
}