在最新的模板约束论文中,提出了一个用于约束模板参数的新工具集。此外,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/