gpt4 book ai didi

C++ 不匹配函数调用

转载 作者:行者123 更新时间:2023-11-28 06:17:33 25 4
gpt4 key购买 nike

我正在制作一个用于介绍 C++ 类的选项模板类,作业的一部分是实现一个 transform() 函数,该函数采用给定函数 (f) 并在给定选项上运行所述函数,然后返回一个新选项包含新值,如果它为空,则返回一个空选项。下面是头文件:

#ifndef OPTION_HPP
#define OPTION_HPP

template<typename T>
class Option {
private:
T *value; // nullptr if the Option is empty.

public:

// Applies f to the value in this Option. Returns a (copy of) this Option if f returns
// true; an empty option otherwise. If this Option is empty and empty Option is returned.
template<typename Function>
Option<T> filter( Function f ) const;

// Applies f to the value in this Option. Returns an Option containing the result of f.
// If this Option is empty an empty Option is returned.
template<typename U, typename Function>
Option<U> transform( Function f ) const;
};





template<typename T>
template<typename U, typename Function>
Option<U> Option<T>::transform( Function f ) const
{
if ( value != nullptr){
return f(value);
}else{
return value;
}
}

#endif

下面是类文件:

#include <string>
#include "Option.hpp"

using namespace std;

Option<unsigned> process_string( const Option<string> &s )
{
// Filter out all strings with a length greater than or equal to 10.
Option<string> s1 = s.filter( [](const string &x) { return x.length()< 10; } );

// Transform the string into its length. Note that we must explicitly provide the type of U
// since the compiler can't deduce that type when it is only used in the return type.
return s1.transform<unsigned>( [](const string &x) { return x.length(); } );
}

int main(){



}

问题出在这部分:

template<typename T>
template<typename U, typename Function>
Option<U> Option<T>::transform( Function f ) const
{
if ( value != nullptr){
return f(value);
}else{
return value;
}
}

我收到的错误是

no match for call to ‘(process_string(const Option >&)::__lambda1) (std::basic_string* const&)’

最佳答案

我遇到了类似的问题,希望这对您有所帮助。您想要将 f 应用于当前选项中的值。在这种情况下,您需要返回一个新选项,其中包含“this”选项中值的拷贝。

template<typename T>
template<typename Function>
Option<T> Option<T>::filter( Function f )const{
T t;

if(f(t) == true){
return Option( *this );
}
else{
return Option();
}

}

关于C++ 不匹配函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29954317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com