注册 登录
编程论坛 C++教室

multiset初始化问题(静态函数作为模板参数)

韩海0312 发布于 2017-05-26 15:05, 2501 次点击
1.出错代码
程序代码:
class Basket {
public:
    void add_item(const std::shared_ptr<Quote> &sale);
    double total_receipt(std::ostream&) const;


private:
    static bool compare(const std::shared_ptr<Quote>& lhs,
                        const std::shared_ptr<Quote>& rhs)
    {return lhs->isbn() < rhs->isbn();}
    std::multiset<std::shared_ptr<Quote>,

                  decltype(compare)*> items (compare); //直接初始化出错
    decltype(compare) *p = compare;//这里没有问题
};
error提示:
error: ‘compare’ is not a type
       decltype(compare)*> items (compare);

2.修改后的代码
程序代码:
class Basket {
public:
    void add_item(const std::shared_ptr<Quote> &sale);
    double total_receipt(std::ostream&) const;


private:
    static bool compare(const std::shared_ptr<Quote>& lhs,
                        const std::shared_ptr<Quote>& rhs)
    {return lhs->isbn() < rhs->isbn();}
    std::multiset<std::shared_ptr<Quote>,

                  decltype(compare)*> items {compare}; // 列表初始化没有问题
    decltype(compare) *p = compare;
};

3. 我在其他地方做得测试
程序代码:
using namespace std;

bool Less(const shared_ptr<Quote> &lhs, const shared_ptr<Quote> &rhs)
{
    lhs->isbn() < rhs->isbn();
}

int main()
{

    multiset<shared_ptr<Quote>, decltype(Less)*> items{Less};// items(Less) 和 items{Less}都可以通过编译
}
请问类的静态函数作为multiset的模板参数和初始换参数时有什么限制么?


[此贴子已经被作者于2017-5-26 15:22编辑过]

5 回复
#2
rjsp2017-05-26 15:39
你的问题就是

int main( void )
{
    int a = 1;
    int b = { 2 };
    int c {3};
    int d( 4 );
}

struct foo
{
    int a = 1;
    int b = { 2 };
    int c {3};
    int d( 4 ); // 为什么这一句不允许吧?语法规定
};
#3
rjsp2017-05-26 16:00
在C++标准中,brace-or-equal-initializer 是个专有名词
#4
rjsp2017-05-26 16:33
语法为什么这规定,有人问过了
https://
https://
https://
#5
韩海03122017-05-26 19:30
回复 4楼 rjsp
又是你,太感谢你了

我找到答案了
The idea is to flat out reject any syntax that could be interpreted as a function declaration. For example,
std::vector<int> ns();
is a function declaration. These aren't:
std::vector<int> ns{};
std::vector<int> ns = std::vector<int>();
For consistency, any member declaration with this form
T t(args...);
is disallowed, which avoids a repeat of the most vexing parse fiasco.
#6
韩海03122017-05-26 19:35
回复 4楼 rjsp
我的代码里
std::multisetstd::shared_ptr<Quote, decltype(compare)*> items (compare);
这个定义有可能被解释称函数了,但是compare又不是一个类型
所以error提示
error: ‘compare’ is not a type
1