c++ - 避免模​​板化类型的过度重复

标签 c++ templates

我想定义一个通用函数,其参数和返回类型是模板的相同实例。这导致了过于冗长的定义。有没有一种方法可以在不污染封闭 namespace 的情况下使用速记?

例子,

template<class CoordinateType, class ValueType>
struct PointWithValue {
    CoordinateType x, y;
    ValueType value;
}

template<class CoordinateType, class ValueType>
PointWithValue<CoordinateType, ValueType> interpolate(
    PointWithValue<CoordinateType, ValueType> point1,
    PointWithValue<CoordinateType, ValueType> point2)
{
    ...
}

我能想到的一个解决方案是

template<class PointWithValueType>
PointWithValueType interpolate(
    PointWithValueType point1, PointWithValueType point2)

但我对此并不满意,因为它混淆了我对 PointWithValueType 的期望;它仅隐式显示在主体函数中。而且,如果调用者传递了错误的参数,则错误不太可能清晰明了。

我想要这样的东西

template<class CoordinateType, class ValueType>
using PointWithValueType = PointWithValue<CoordinateType, ValueType>;
PointWithValueType interpolate(
    PointWithValueType point1, PointWithValueType point2)

据我所知,只有当我将它包装在一个类中并将该方法定义为 static 时,以上内容才有效。它有点工作,但它也改变了接口(interface)(将函数放在更深的命名范围内)并且它依赖于一个没有成员且只有一个静态函数的类,这感觉很尴尬并且可能会让用户感到困惑。

这是一个一般性问题,不适用于此类问题的特定问题的解决方法不是合适的答案。是否有类似于我的 using 示例但没有缺点的东西?

最佳答案

有了 traits 和 SFINAE,你可能会做

template <typename T>
struct IsPointWithValue : std::false_type {};

template <class CoordinateType, class ValueType>
struct IsPointWithValue<PointWithValue<CoordinateType, ValueType>> : std::true_type
{
// Possibly aliases to retrieve template parameters.
};

template<class T, std::enable_if_t<IsPointWithValue<T>::value, int> = 0>
T interpolate(T point1, T point2);

关于c++ - 避免模​​板化类型的过度重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57659775/

相关文章:

c++ - Zebra KBTools MC92N0 键盘重新映射 C++ -- "error.h"没有这样的文件或目录

模板的 C++ 错误和推导的参数冲突类型

c++ - 库使用的模板实例化

c++ - 将声明为 `extern char[]` 的变量传递给 VC++ 中的函数模板时出错

javascript - Grails如何让AJAX发送从模板表单中编辑的对象

wpf - 通过两个级别绑定(bind)到 TemplatedParent

c++ - 如何在QGLWidget中缩放和滚动

c++ - 用于 C/C++ 的类 CoffeeScript 语言

c++ - 使用 C++ 代码中的参数调用 masm 函数

c++ - 优先队列排序 [C++]