c++ 如何检查类是否有给定名称和输入参数的方法,但任何返回类型?

yfjy0ee7  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(118)

我使用C++20,所以我可以使用概念,这是更可取的。我想检查类Token是否有方法<ANY> get_executor();,并将结果传递给if constexpr,所以它应该是这样的:

class Token;

template <typename T>
concept has_method_get_executor = <???>;

if constexpr (has_method_get_executor<Token>())
{
...
}
else
{
...
}

我怎么能写出这样的概念呢?如果没有概念更容易,我愿意接受建议。

k97glaaz

k97glaaz1#

重载或私有类方法可能会有一些复杂性,但基本用例相当简单:

#include <iostream>

template<typename T>
concept has_method_get_executor = requires(T &&t) {
    {t.get_executor() };
};

class Token {

public:
    bool get_executor();
};

class Token2 {};

bool foo()
{
    if constexpr (has_method_get_executor<Token>)
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool foo2()
{
    if constexpr (has_method_get_executor<Token2>)
    {
        return true;
    }
    else
    {
        return false;
    }
}

int main()
{
    std::cout << foo() << "\n"; // Result: 1
    std::cout << foo2() << "\n"; // Result: 0
    return 0;
}

相关问题