泛型类中的语法

ano*_*est 0 c++ templates comparator

我试图用模板解决一个练习.我的代码在大多数情况下运行良好,但我发现有一个案例无效,这是我的代码的一部分.默认比较器是<.

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;
 };
Run Code Online (Sandbox Code Playgroud)

代码工作几乎是所有情况.为例: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 );
 }
Run Code Online (Sandbox Code Playgroud)

例:

Myclass <list<string>, another> t6 ( list<string>{"foo","done"}, another ( false )) ;
Run Code Online (Sandbox Code Playgroud)

我收到这个错误.

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
Run Code Online (Sandbox Code Playgroud)

我试图重写代码,但我不明白如何解决这个问题.

Woj*_*wka 5

问题是你没有在构造函数中使用初始化列表,所以MyClass的成员是用它们的默认构造函数构造的,然后才从参数中复制.使用

Myclass ( const type1 & arg1,const typecomparator & comparator = typecomparator () )
 : seq(arg1), comp(comparator)
{
}
Run Code Online (Sandbox Code Playgroud)

并且another不再需要默认构造函数.