【发布时间】:2019-06-21 23:01:10
【问题描述】:
我正在寻找一种在每次实例化模板时自动使默认模板参数唯一的方法。由于 lambda 表达式创建的未命名函数对象具有不同的类型,我想以某种方式采用它们。随着最近对标准 daft 的更改删除了 “lambda 表达式不应出现在...模板参数” 限制(请参阅Wording for lambdas in unevaluated contexts),这似乎是个好主意。所以我写了以下有点工作的sn-p compiles on recent gcc and clang:
#include <type_traits>
template<void ( * ) (void) = [](){}> class
unique final {};
static_assert(false == ::std::is_same_v<unique<>, unique<>>);
int main()
{
return 0;
}
这是一种可行的方法还是那些“格式不正确,不需要诊断”的案例之一?
一些额外的上下文:我想用它来实现应该在单个翻译单元中工作的 Ada 风格的强类型定义,而无需手动发明否则将不使用的唯一标签:
struct _tag_WowInt {};
using Int = type<int, _tag_WowInt>;
struct _tag_SoUnique {};
using DifferentInt = type<int, _tag_SoUnique>;
Upd1:我想提一下,涉及__COUNTER__ 或类似宏的方法在一般情况下不起作用,因为它们只会被预处理器扩展一次并且won't yield unique types when used inside of template for example。
【问题讨论】:
-
msvc 和 edg 甚至出于不同的原因拒绝您的代码;有趣。
标签: c++ templates lambda language-lawyer c++20