c++03中模板化方法中的动态返回类型
最近我的任务是将我的一些代码从C++14重写到C++03,这样我就可以利用它了。但是,我不确定这段代码是否可以在不使用auto的情况下重写 我有一个模板类字段c++03中模板化方法中的动态返回类型,c++,C++,最近我的任务是将我的一些代码从C++14重写到C++03,这样我就可以利用它了。但是,我不确定这段代码是否可以在不使用auto的情况下重写 我有一个模板类字段,它是类型的容器。代码段中的方法将两个字段的求和行为定义为字段中每个条目逐点的总和 类型,可以是双精度的,也可以是自行设计的类向量。这个 向量+向量、向量+双向量和双向量的行为在类向量的定义中有完整的定义 代码片段能够完全定义应用程序的预期行为 四种可能情况下的字段总和: 字段+字段, 场+场, 字段+字段, 字段+字段 这是通过创建响应字
template< typename Type_1, typename Type_2 > const auto operator+ (
const Field< Type_1 >& lhs, const Field< Type_2 >& rhs ) {
auto response = Field <
typename std::remove_const<decltype( lhs.get(0) + rhs.get(0) )>::type
>( lhs.size() );
for( size_t i = 0; i < lhs.size(); i++ ){
response[i] = lhs.get(i) + rhs.get(i);
}
return response;
}
我敢肯定你在这里运气不好。问题主要在于,如果不指定返回类型,就无法选择运算符+的特定重载,因此无法在C++03中单独检索它 但是,您可以做的是编写一个元函数来提供正确的返回类型。如果您还使用此函数定义运算符+重载,您将获得相同的编译时保证和足够好的错误:
template <typename Lhs, typename Rhs>
struct AddResult;
template <>
struct AddResult<Vector, Vector> { typedef Vector result_type; }
// ...
typename AddResult<Vector, Vector>::result_type operator+(Vector lhs, Vector rhs)
// ...
template< typename Type_1, typename Type_2 >
Field<typename AddResult<Type_1, Type_2>::result_type>
operator+ (const Field<Type_1>& lhs, const Field<Type_2>& rhs)
{
Field<typename AddResult<Type_1, Type_2>::result_type> response(lhs.size());
for (size_t i = 0; i != lhs.size(); i++) {
response[i] = lhs.get(i) + rhs.get(i);
}
return response;
}
非常不漂亮,但我想不出更好的解决方案。您总是可以用显式类型替换auto。 在这种情况下,您可以在模板的前面添加模板参数,以便仍然可以推断Type1和Type2,并在调用站点指定结果类型
template<typename Result, typename Type_1, typename Type_2 >
const Result operator+ ( const Field< Type_1 >& lhs, const Field< Type_2 >& rhs ) ...
我认为这个解决方案是理想的。如果我做了如下操作:Field