首页 > 解决方案 > 如何使用c++20概念匹配一个类的泛型成员函数

问题描述

我有一个模板类 Foo,包括一个可以接受任何 ARGS 的泛型函​​数 calc

template <class RET>
struct Foo
{
    template<class ...ARGS>
    RET calc(ARGS &&...args)
    {
        // do some thing...
        ((std::cout<<", "<<std::forward<ARGS>(args)), ...) <<std::endl;
        return defaultRet;
    }

    RET defaultRet;
};

int main () {
    auto ret = Foo<int>(42).calc(1,2,3); // print "1, 2, 3"
    std::cout<< ret <<std::endl;        // print "42"
    return 0;
}

然后我想写一个概念Calcable来匹配Foo。然后Bar::calc返回voidCalcable<Bar<int>>应该是这样false

但是我写不出来Calcable,我疯了!

template <class RET>
struct Foo
{
    template<class ...ARGS>
    RET calc(ARGS &&...args)
    {
        // do some thing...
        ((std::cout<<", "<<std::forward<ARGS>(args)), ...) <<std::endl;
        return defaultRet;
    }

    RET defaultRet;
};

template <class RET>
struct Bar
{
    
};

template <class T>
concept Calcable = ??  // <<<<<<<<<<<< How to match generics function calc?

template <Calcable T>
struct Check
{

};

int main () {
    auto ret = Foo<int>(3).calc(1,2,3);  // ok
    std::cout<< ret <<std::endl;         // ok

    using YES = Check<Foo<int>>;         // I need compile pass
    using NO = Check<Bar<int>>;          // I need compile error
    return 0;
}

我一直在找它一整天,但没有

标签: c++templatesgenericsc++20concept

解决方案


推荐阅读