是否有可能在c ++(20)中定义(无序)类型对,从而允许通过在编译时提供其任何成员来找到这样的一对?
这很简单,可以为每个无序对手动定义两个有序对,也可以在一个位置定义完整的一对对,例如作为元组的模板参数:
通过专业化对(A,B)的定义:
template<>
struct find_pair<A> {
using p = std::pair<A,B>;
};
template<>
struct find_pair<B> {
using p = std::pair<A,B>;
};
获取(A,B):
find_pair<A>::p
或
find_pair<B>::p
通过可变参数模板对完整对的定义:
template<typename A, typename B, typename ... X>
struct some_binary_relation : some_binary_relation<X...> {
template<>
static std::pair<A,B> p<A>();
template<>
static std::pair<A,B> p<B>();
};
using rel1 = some_relation<A,B,F,G,M,N>;
decltype(rel1::p<G>()) x //std::pair<F,G>
方法#1的优点在于,可以将一对的每个定义分开,但需要冗余/膨胀的语法。方法2要求每种类型只能写入一次,但是必须手动将所有对存储在模板参数列表中(不灵活)。
是否有可能以某种方式线对定义可以彼此分开对定义中是否不需要重复的代码?
当然,没有两个不同的对必须包含相同的类型,并且不必支持搜索不存在的对。
不确定您的实际需求,但这可能会有用:
#include <utility>
namespace pair {
template<class T> struct Type {};
template<class A, class B>
struct Pair {
Pair(Type<A>);
Pair(Type<B>);
using type = std::pair<A, B>;
};
} // pair
namespace detail {
struct NotRegistered {
using type = void;
};
NotRegistered FindPairImpl(...);
template<class A>
auto FindPairImpl(pair::Type<A> a) -> decltype(RegisterPair(a));
} // namespace detail
template<class PairedType>
using FindPair = typename decltype(detail::FindPairImpl(pair::Type<PairedType>()))::type;
定制点:在Pair<Type1, Type2> RegisterPair(Pair<Type1, Type2>)
命名空间中定义函数pair
。
然后使用FindPair
元函数查找类型的对:
namespace pair { Pair<double, const char *> RegisterPair(Pair<double, const char *>); }
int main() {
static_assert(std::is_same<FindPair<int>, void>::value);
static_assert(std::is_same<FindPair<double>, std::pair<double, const char *>>::value);
static_assert(std::is_same<FindPair<const char *>, std::pair<double, const char *>>::value);
}