首页 > 解决方案 > 检查嵌套类模板的概念

问题描述

假设我希望能够写:

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ᐳ&lt;T::template nested>;

但这会在 gcc 中产生误报(int例如,该概念错误地接受 ),很难给辅助概念起一个合理的名称,现在它的定义可能与使用它的地方有所不同。

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

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

但这目前在 clang 中不起作用(它不喜欢未评估的上下文中的 lambdas),非常丑陋,而且读者可能不清楚。

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

我可能应该提到,作为测试实例化 T::template nested是行不通的,因为它受到约束是合法的。

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

解决方案


制作一个采用 a 的模板化结构template <class> class并检查该结构是否可以实例化:

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

编译器资源管理器链接


推荐阅读