可以在Haskell(模板专业化)中模拟使结构“对应”类型的C++模式吗?
template <typename T>
struct Corresponding;
template <>
struct Corresponding<int> {
using CorrespondingT = boost::multiprecison::cpp_int;
};
template <typename T> using GetCorresponding = typename Corresponding<T>::CorrespondingT;
这可以用作
static_assert(std::is_same_v<GetCorresponding<int>, boost::multiprecision::cpp_int>); // true
在编译时解析的Corresponding<T>包含具有相应类型的别名的结构在哪里T。另一个例子是std::remove_ptr_t<T*>对应于T
我可以在 Haskell 中做类似的事情吗,例如
iAmAnInteger :: getCorresponding Int -- Integer
?
我不熟悉 Haskell 的编译时类型功能,但这可能吗?
回答
我不精通 C++,所以我不能 100% 确定您的示例代码在做什么,但乍一看类型系列和等式似乎相似。
{-# LANGUAGE TypeFamilies #-}
type family Corresponding a
type instance Corresponding Int = Integer
foo :: Corresponding Int ~ Integer => ()
foo = () -- compiles
bar :: Corresponding Int ~ Bool => ()
bar = () -- type error at any use site
baz :: Corresponding Int
baz = toInteger 3 -- compiles
quux :: Corresponding Int
quux = False -- type error
THE END
二维码