在定义可交换操作时减少代码重复

时间:2017-07-06 08:16:14

标签: c++ templates metaprogramming

我有一组名为overlap的可交换二进制函数的重载,它接受两种不同的类型:

class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);

当且仅当一个形状与另一个形状重叠时,我的函数overlap才返回true - 这是讨论multimethods时使用的一个常见示例。

因为overlap(a, b)等同于overlap(b, a),所以我只需要实现关系的一个“侧”。一个重复的解决方案是写这样的东西:

bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b);   }

但是我不想通过允许使用模板来生成相同函数的额外N! / 2个简单版本。

template <typename T, typename U> 
bool overlap(T&& t, U&& u) 
{ return overlap(std::forward<U>(u), std::forward<T>(t)); }

不幸的是,这很容易无限地递归,这是不可接受的:见 http://coliru.stacked-crooked.com/a/20851835593bd557

如何防止这种无限递归?我是否正确地解决了这个问题?

3 个答案:

答案 0 :(得分:64)

这是一个简单的解决方法:

template <typename T, typename U> 
void overlap(T t, U u)
{
    void overlap(U, T);
    overlap(u, t);
}

模板本身声明了目标函数,它比递归更受欢迎,因为它是完全匹配的(在实际情况下一定要注意constness和reference-ness)。如果尚未实现该函数,则会出现链接器错误:

/tmp/cc7zinK8.o: In function `void overlap<C, D>(C, D)':
main.cpp:(.text._Z7overlapI1C1DEvT_T0_[_Z7overlapI1C1DEvT_T0_]+0x20):
    undefined reference to `overlap(D, C)'
collect2: error: ld returned 1 exit status

...直接指向缺失的函数:)

答案 1 :(得分:13)

正如一位聪明人曾经说过的那样,除了太多的间接层外,没有任何问题你无法通过额外的间接层来解决。

所以,使用SFINAE和一些间接来完成它:

template<class A, class B>
auto overlap(A&& a, B&& b)
-> decltype(overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)))
{ return overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(int, A&& a, B&& b)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(long, B&& b, A&& a)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

// You can provide more choices if you want, for example to use member-functions.

// Implement `do_overlap(A, B)`, maybe with references, in at least one direction.

答案 2 :(得分:1)

您可以将实际方法重命名为overlap_impl,并在模板中调用此方法。我将打破递归:

bool overlap_impl(A a, B b) { /* check for overlap */ }

template <typename T, typename U> 
bool overlap(T&& t, U&& u) 
{ return overlap_impl(std::forward<U>(u), std::forward<T>(t)); }

template<> bool overlap(A&& t, B&& u)
{ return overlap_impl(std::forward<A>(t), std::forward<B>(u)); }