避免过多重复使用模板类型

pat*_*gan 5 c++ templates

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

例,

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)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我可以提出的一种解决方案是

template<class PointWithValueType>
PointWithValueType interpolate(
    PointWithValueType point1, PointWithValueType point2)
Run Code Online (Sandbox Code Playgroud)

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

我想要看起来像这样的东西

template<class CoordinateType, class ValueType>
using PointWithValueType = PointWithValue<CoordinateType, ValueType>;
PointWithValueType interpolate(
    PointWithValueType point1, PointWithValueType point2)
Run Code Online (Sandbox Code Playgroud)

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

这是一个普遍的问题,不适用于此类问题的解决方法不适用于该特定问题。是否有与我的using示例相似但没有缺点的内容?

Jar*_*d42 5

使用特质和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);
Run Code Online (Sandbox Code Playgroud)