我试图用模板解决一个练习。 我的代码在大多数情况下运行良好,但我发现有一个案例无效,这是我的代码的一部分。 默认比较器是<。
template <typename type1, typename typecomparator=less<typename type1::valuetype1> >
class Myclass
{
public:
Myclass ( const type1 & arg1,const typecomparator & comparator = typecomparator () )
{
this->seq=arg1;
this->comp=comparator;
}
~Myclass ( void ){}
// ...
private:
mutable type1 seq;
typecomparator comp;
};
代码工作几乎是所有情况。
例如:Myclass <string> test ( "abcabcabc" );
但是当我想要使用一个类时:
class another
{
public:
another ( bool caseSensitive )
: m_CaseSensitive ( caseSensitive ) { }
bool operator () ( const string & a, const string & b ) const
{
return m_CaseSensitive ? strcasecmp ( a . c_str (), b . c_str () ) < 0 : a < b ;
}
bool m_CaseSensitive;
};
bool upperCaseCompare ( const char & a, const char & b )
{
return toupper ( a ) < toupper ( b );
}
示例:
Myclass <list<string>, another> t6 ( list<string>{"foo","done"}, another ( false )) ;
我收到此错误。
index.cpp: In constructor ‘Myclass<type1, typecomparator>::Myclass(const type1&, const typecomparator&) [with type1 = std::list<std::basic_string<char> >, typecomparator = another]’:
index.cpp:67:136: instantiated from here
index.cpp:20:4: error: no matching function for call to ‘another::another()’
index.cpp:20:4: note: candidates are:
index.cpp:50:20: note: another::another(bool)
index.cpp:50:20: note: candidate expects 1 argument, 0 provided
index.cpp:47:7: note: constexpr another::another(const another&)
index.cpp:47:7: note: candidate expects 1 argument, 0 provided
index.cpp:47:7: note: constexpr another::another(another&&)
index.cpp:47:7: note: candidate expects 1 argument, 0 provided
我试图重写代码,但我不明白如何解决这个问题。
答案 0 :(得分:5)
问题是你不在构造函数中使用初始化列表,所以MyClass的成员用它们的默认构造函数构造,然后才从参数中复制。使用
Myclass ( const type1 & arg1,const typecomparator & comparator = typecomparator () )
: seq(arg1), comp(comparator)
{
}
并且不再需要another
的默认构造函数。
答案 1 :(得分:1)
默认为赋值构造函数
another ( const another& ) = default;