[英]C++ distinguish Functor and Value template argument
一般來說,我在理解仿函數方面遇到了一些麻煩,因為我對模板編程很新。
我在這里要完成的是以下內容,我正在嘗試使用一個函數來獲取一個Functor和一個帶有值的重載函數。
理想情況下:
template<typename ValueType>
int function(ValueType v)
{
v + 1;
...
}
template<typename Functor>
int function(Functor f)
{
f();
...
}
我可以通過將std :: function作為參數來獲得性能,但我特別希望能夠將lambda作為參數。
編輯
我想要實現的是允許我正構建的構造在必要時進行惰性求值:
construct.option(1)
construct.option([](){ return 5;})
construct.value()
使用構造選擇在調用選項時獲取哪個參數的值。 (可能有一個額外的參數來確定是否選擇了該選項)
要明確的是,只要完成此選項調用,它就會知道是否評估表達式。
此外,如果參數重載了()運算符,我想調用它,無論它是否也重載+ 1。
是的,你可以使用SFINAE做到這一點:
// overload taking functor f(int)
template<typename Func>
std::result_of_t<Func(int)> // or std::invoke_result_t<> (C++17)
function(Func const&func)
{
return func(0);
}
// overload taking value of builtin arithmetic type
template<typename ValueType>
enable_if_t<std::is_arithmetic<ValueType>::value, ValueType>
function(Value const&val)
{
return val;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.