2016-04-24 45 views
0

我试图弄清楚为什么当你访问名为asdf的std::set的数组时,这段代码不能编译。但是,如果您尝试访问asdf的元素(如本示例中的索引0),则无法使用函数getItem编译代码。编译器会抛出这个错误。std :: set和比较器数组

main.cpp(21): error C2440: 'return': cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>> &' 
     with 
     [ 
      _Kty=test * 
     ] 
main.cpp(21): note: Reason: cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>>' 
     with 
     [ 
      _Kty=test * 
     ] 
main.cpp(21): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 

这里是例子:

#include <set> 

struct test { 
    int idx; 
    struct compare { 
     bool operator()(const test* a, const test* b) { 
      return a->idx < b->idx; 
     } 
    }; 
}; 


class asdf123 { 
public: 
    asdf123() { 

    } 

    const std::set<test*>& getItem() const 
    { 
     return asdf[0]; 
    } 

private: 
    typedef std::set<test*, test::compare> stuffType[100]; 
    stuffType asdf; 
}; 

int main() { 
    asdf123 a; 
    return 0; 
} 

没有代码工作正常的比较。

回答

0

std::set<test*, test::compare>std::set<test*>是不同的类型,不能隐式地从一个转换到另一个,这就是编译器抱怨的原因。

std::set有两个默认的模板参数,所以std::set<test*, test::compare>

std::set<test*, test::compare, std::allocator<test*>> 

std::set<test*>

std::set<test*, std::less<test*>, std::allocator<test*>> 

你可能的getItem()返回类型更改为const std::set<test*, test::compare>&来解决这个问题。

+1

您可能想对此进行扩展:没有从这两种类型到另一种类型的隐式转换,因此编译错误。 – Peter

+0

哇,我怎么错过他们有不匹配的类型?我想我更关注于试图找出隐藏的编译器错误是什么。 –

+0

@BrandanTylerLasley错误消息中仍然有提示,尤其是它显示了未能转换的两种类型, – songyuanyao