繁体   English   中英

C++模板; 作为模板参数传递的 function 的自动推导返回类型;

[英]C++ Template; Auto deduction return type of function passed as template argument;

我需要扣除一个getter function的返回值类型。 该 getter 作为模板列表中的 function 指针传递。

所以吸气剂看起来像:

using TGetter   = std::function<std::string(Me*)>;

std::string getter(Me* me)
{
    return std::string("string");
}

模板 class

template<typename TGetter>
class Handler
{
public:
    Handler(TGetter getter)
        :m_getter(getter)
    {};

    using TValue =  std::string;  //decltype(TGetter()); <- something like that I want to get

private:
    TGetter                     m_getter;
    ...

    bool handler();

实例化是这样的:

Handler<TGetter> h(getter);

我想要的是根据 getter 返回类型声明TValue 所以std::string就像例子中的 getter 一样。 我将拥有不同类型的 getter,并希望像TValue value; 在 class 内部。

using TValue = decltype(TGetter()); 被解析为 function 指针。

你能帮我把它弄对吗,谢谢。

如果您的 function 没有 arguments,则只需使用std::declval declval :

using TValue = decltype(std::declval<TGetter>()(/* your args go here */));

您可以使用std::invoke_result (C++17 起)。

using TValue = std::invoke_result_t<TGetter, Me*>;

在 C++17 您使用std::result_of之前,请注意它在 C++17 中已弃用,并且其用法与std::invoke_result不同。

using TValue = std::result_of_t<TGetter(Me*)>;

如果您只使用std::function ,您可能会这样做:

template <typename TGetter> class Handler;

template <typename Ret, typename ... Ts>
class Handler<Ret(Ts...)>
{
public:
    using TGetter = std::function<Ret(Ts...)>;

    Handler(TGetter getter) : m_getter(getter) {}

    using TValue = Ret;

private:
    TGetter                     m_getter;
    // ...

    bool handler();
};

使用Handler<std::string(Me*)> h(&getter);

如果您想要任何可调用类型,则:

template <typename TGetter>
class Handler
{
public:
    Handler(TGetter getter) : m_getter(getter) {}

    using TValue = decltype(declval<TGetter>()(/*args*/));

private:
    TGetter                     m_getter;
    // ...

    bool handler();
};

您正在寻找的是result_type ,可能是:

//...
public:
  using TValue =  typename TGetter::result_type;
//...

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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