c++ - 检查嵌套类模板的概念

标签 c++ c++20 c++-concepts

假设我希望能够写:

template<class T> concept WithNestedTemplate = ...;
struct F { template<class> using nested = int; };
static_assert(WithNestedTemplate<F>);
static_assert(!WithNestedTemplate<int>);

WithNestedTemplate应该检查 T::template nested 是否存在带有签名的成员类模板或别名模板 template<class> class .

我可以写一个辅助概念:

template<template<class> class> concept TemplateOfᐸclassᐳ = true;
template<class T> concept WithNestedTemplate = TemplateOfᐸclassᐳ<T::template nested>;

但这会在 gcc 中产生误报(例如,该概念错误地接受了 int ),很难为帮助器概念指定一个合理的名称,现在它的定义可能与它的使用位置有一定距离。

或者我可以用tparams 编写一个通用的 lambda:

template<class T> concept WithNestedTemplate = requires {
    []<template<class> class>(){}.template operator()<T::template nested>(); };

但这目前在 clang 中不起作用(它不像未计算上下文中的 lambda),非常丑陋,读者可能不清楚。

有没有更好的方法来做到这一点 - 最好是适用于所有主要编译器的方法?

我应该提一下实例化 T::template nested因为测试不会起作用,因为对其进行约束是合法的。

最佳答案

使用 template <class> class 制作模板结构并检查该结构是否可以实例化:

template <template <class> class> struct TakesTemplate {};
template<class T> concept WithNestedTemplate = requires {
    typename TakesTemplate<T::template nested>;
};

Compiler Explorer link

关于c++ - 检查嵌套类模板的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67615629/

相关文章:

c++ - C++20 中 "Relation"概念定义背后的动机

c++ - #define 字符串的类型是什么?

c++ - 子模块 : how to divide C++ module into submodules

c++ - 为什么 C++20 中不推荐使用 volatile?

c++ - 函数模板取函数模板

c++ - C++20 中概念的语法

c++ - 继承层次结构与多重继承 (C++)

c++ - 如何输出属于 vector 数组的结构字符串?

Android 标准和 STL 支持

c++ - 检查 char 数组中前导字符的最快方法是什么?