简体   繁体   中英

Deduce template parameter from concept

I'm learning templates and concepts. I'm trying to make a concept for types that are derived from a class, but this class is a template.

template<typename T>
struct CAA{};

template<typename T, typename T2>
concept DerivedFromAA = requires() {std::derived_from<CAA<T2>,T>;};

Is it possible to use such concept in a function without having to explicitly tell it the template type of the class? Is my idea wrong on how to define such concept?

template<typename T>
void conceptTestFunc(DerivedFromAA<T> auto& aa)
{
}

//...

CAA<int> aa;
conceptTestFunc<int>(aa); // Without having to tell it "int"

(I'm compiling this with Clang.)

A template is not a type.

So if CAA is a template, then CAA<int> would be a type.

A type can't be derived from a template, only from another type. This means that the check has to be done on the type, not the template.

If you on the other hand want to deduce the inner type of aa , that can be done.

#include <concepts>

template<typename T>
struct CAA{};

template<typename T>
struct CBB{};

template<typename T, typename T2>
concept DerivedFromAA = std::derived_from<CAA<T2>,T>;

template<template <typename> typename Outer, typename T>
requires DerivedFromAA<Outer<T>, T>
void conceptTestFunc(Outer<T>& aa)
{
}

int main() {
    CAA<int> aa;
    conceptTestFunc(aa);
    CBB<int> bb;
    conceptTestFunc(bb); // This fails
}

You might do

template<typename T>
concept DerivedFromAA = requires(T t) {[]<typename U>(CAA<U>&){}(t);};

static_assert(DerivedFromAA<CAA<int>>);

Demo

gcc dislikes lambda in requires, so you might create dummy helper function outside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM