Cli*_*ton 3 c++ expression-templates c++11
有没有办法创建一个类型A:
鉴于:
A f(...);
然后:
双方auto&& a = f(...);并const auto& a = f(...);给出一个编译错误?
这样做的原因是,在这种情况下,A是一个表达式模板,其中包含对temporaries(作为参数提供f)的引用,因此我不希望此对象的生命周期超出当前表达式.
注意我可以auto a = f(...);通过将As复制构造函数设为私有来防止成为问题,并f(...)在需要时成为A的朋友.
代码示例 (ideone链接):
#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>();
}
Run Code Online (Sandbox Code Playgroud)
给定任何临时对象,在C++中通过将其绑定到const&或&&变量来延长该临时对象的生命周期始终是合法的.最终,如果你正在处理懒惰的评估等,你必须要求用户不要使用const auto &或auto &&.C++ 11中没有任何东西允许你强行阻止用户这样做.
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |