c++ - 可以在 Haskell 中模拟 'correspond' 类型的 C++ 结构模式(模板特化)吗?

标签 c++ haskell template-specialization compile-time static-typing

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/

相关文章:

如果不包含函数列表,C++ 程序将无法编译

c++ - char变量和if语句错误C++

c++ - 在 MacOS 10.9 (Mavericks) 上构建 Boost.Python 应用程序

Haskell:仅当自上次执行以来经过一定时间后才执行IO操作

c++ - 在这种特殊情况下,为什么不需要将 std::hash() 的特化注入(inject)到 std namespace 中?

c++ - 将 R 代码转换为 C++ 以进行 Rcpp 实现

list - "takeWhile"在列表理解中

Haskell:GHCi 将 Ctrl-Y 视为 Ctrl-Z

c++ - 在 C++03 中,如何根据类型特征有条件地声明模板类的静态数据成员

c++ - 在 Doxygen 输出中隐藏模板特化参数