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
关于c++ - 可以在 Haskell 中模拟 'correspond' 类型的 C++ 结构模式(模板特化)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67076386/