[英]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();
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.