c++ - 模板约束是否可用于变量模板?

标签 c++ c++14 type-constraints c++-concepts

在最新的模板约束论文中,提出了一个用于约束模板参数的新工具集。此外,C++14 中还提供了变量模板。变量模板允许定义类型参数化常量等。

没有提及这些功能如何交互。使用 pi 的规范示例,我们可以得到:

template<Integral T>
  constexpr double pi(3.141592653589793238);

template<Floating_point T>
  constexpr T pi(3.1415926535897932384626433832795029L);

这将强制 C/C++ 数值从整型转换为 double 型。它还会阻止完全不相关的类型的实例化。 (看看这个,我们可能想用需要浮点 vector 的东西替换 Floating_point 以支持复数。)

我是否遗漏了其中一篇论文中的某些内容,或者该内容正在开发中?也许它是免费的并且不值得一提?

最佳答案

在提案的最新版本(N4040,日期为 2014 年 5 月)中,答案是:

5 A variable template has the following restrictions:

— The template must be unconstrained.

— The declared type must be bool.

— The declaration must have an initializer.

— The initializer shall be a constraint-expression.

[ Example:

template<typename T>
concept bool D1 = has_x<T>::value; // OK

template<typename T>
concept bool D2 = 3 + 4;           // Error: initializer is not a constraint

template<Integral T>
concept bool D3 = has_x<T>::value; // Error: constrained concept definition

— end example ]

关于c++ - 模板约束是否可用于变量模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17865724/

相关文章:

c++ - 包装接收纯右值的函数时省略复制/移动

haskell - 约束操作包

c# - 我可以定义一个只接受原始类型的方法吗?

c++ - 解析除关键字之外的标识符

使用类型约束的 F# 模式匹配

c++ - 何时在全局范围内使用 new

c++ - 如何在参数非常量中传递 const 指针

c++ - 检查字符串是否相同C++

android - 尽管已正确保存,但文件没有出现在 SD 卡上;出现在设备上的文件资源管理器中

c++ - 函数参数列表中的 auto 暗示模板参数