Function object as const&
От: McSeem2 США http://www.antigrain.com
Дата: 10.11.10 15:43
Оценка:
Вопрос к всезнающим буквоедам по стандарту.

template<class Array, class Less> 
void Sort(Array& arr, const Less& less)


При этом функтор такой:

bool Cmp(const SortType& a, const SortType& b)
{
    return a.Key < b.Key;
}
. . .
Sort(array, Cmp);


То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?
McSeem
Я жертва цепи несчастных случайностей. Как и все мы.
Re: Function object as const&
От: Vamp Россия  
Дата: 10.11.10 15:47
Оценка: :)
MS>То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?
А почему бы этому не быть легальным? В чем проблема-то собственно?
Да здравствует мыло душистое и веревка пушистая.
Re: Function object as const&
От: blackhearted Украина  
Дата: 10.11.10 15:56
Оценка:
Здравствуйте, McSeem2, Вы писали:

MS>Вопрос к всезнающим буквоедам по стандарту.


MS>
MS>template<class Array, class Less> 
MS>void Sort(Array& arr, const Less& less)
MS>


MS>При этом функтор такой:


MS>
MS>bool Cmp(const SortType& a, const SortType& b)
MS>{
MS>    return a.Key < b.Key;
MS>}
MS>. . .
MS>Sort(array, Cmp);
MS>


MS>То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?


А почему бы и нет? Что смущает?
... << RSDN@Home 1.2.0 alpha 4 rev. 1446>>
Re[2]: Function object as const&
От: McSeem2 США http://www.antigrain.com
Дата: 10.11.10 16:02
Оценка:
Здравствуйте, Vamp, Вы писали:

MS>>То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?

V>А почему бы этому не быть легальным? В чем проблема-то собственно?

G++ v4.2.1 не хочет есть. http://dinkumware.com/exam/ — с "const Less&" — не ест, с просто "Less&" — нормально.
McSeem
Я жертва цепи несчастных случайностей. Как и все мы.
Re[3]: Function object as const&
От: Vamp Россия  
Дата: 10.11.10 16:12
Оценка:
MS>G++ v4.2.1 не хочет есть. http://dinkumware.com/exam/ — с "const Less&" — не ест, с просто "Less&" — нормально.


#include <iostream>
#include <vector>
using namespace std;

template<class Array, class Less> 
void Sort(Array& arr, const Less& less) {}
 
struct SortType {
   int Key;
};

bool Cmp(const SortType& a, const SortType& b)
{
    return a.Key < b.Key;
}

int main()
    {
 vector<int> array;
 Sort(array, Cmp);

    }


Комо жрет.
Да здравствует мыло душистое и веревка пушистая.
Re[3]: Function object as const&
От: Lorenzo_LAMAS  
Дата: 10.11.10 16:14
Оценка:
MS>G++ v4.2.1 не хочет есть. http://dinkumware.com/exam/ — с "const Less&" — не ест, с просто "Less&" — нормально.

14.8.2.1

If P is a reference type, the type referred to by P is used for type deduction.


...

If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.


с более поздней версией г++ нет проблем
Of course, the code must be complete enough to compile and link.
Re[4]: Function object as const&
От: Lorenzo_LAMAS  
Дата: 10.11.10 16:22
Оценка:
Здравствуйте, Lorenzo_LAMAS, Вы писали:

MS>>G++ v4.2.1 не хочет есть. http://dinkumware.com/exam/ — с "const Less&" — не ест, с просто "Less&" — нормально.


L_L>14.8.2.1


L_L>

L_L>If P is a reference type, the type referred to by P is used for type deduction.


L_L>...


L_L>

L_L>If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.


L_L>с более поздней версией г++ нет проблем


вру, версия 4.1.2, 4.4.5 — тоже нормально.
Of course, the code must be complete enough to compile and link.
Re: Function object as const&
От: korzhik Россия  
Дата: 10.11.10 16:22
Оценка: +1
Здравствуйте, McSeem2, Вы писали:

MS>Вопрос к всезнающим буквоедам по стандарту.


MS>
MS>template<class Array, class Less> 
MS>void Sort(Array& arr, const Less& less)
MS>


MS>При этом функтор такой:


MS>
MS>bool Cmp(const SortType& a, const SortType& b)
MS>{
MS>    return a.Key < b.Key;
MS>}
MS>. . .
MS>Sort(array, Cmp);
MS>


MS>То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?


всё вроде хорошо. лезть в стандарт чего то лень.
могу только добавить что я бы написал так:
 Sort(array, &Cmp);
Re[3]: Function object as const&
От: korzhik Россия  
Дата: 10.11.10 20:05
Оценка: 13 (1)
Здравствуйте, McSeem2, Вы писали:

MS>Здравствуйте, Vamp, Вы писали:


MS>>>То, что написано, аргумент типа "const Less& less" — это легально в C++? Мне не интересны мнения, насколько это плохо или хорошо с точки зрения дизайна, меня интересует, насколько это легально с точки зрения буквы стандарта?

V>>А почему бы этому не быть легальным? В чем проблема-то собственно?

MS>G++ v4.2.1 не хочет есть. http://dinkumware.com/exam/ — с "const Less&" — не ест, с просто "Less&" — нормально.


Максим, напиши так: Sort(array, &Cmp); и всё заработает
Re: Function object as const&
От: Masterkent  
Дата: 10.11.10 20:57
Оценка: 54 (7) +1
McSeem2:

MS>Вопрос к всезнающим буквоедам по стандарту.


MS>То, что написано, аргумент типа "const Less& less" — это легально в C++?


Общество Всезнающих Буквоедов По Стандарту даёт тебе следующий ответ:

В C++03 cv-qualified типы функций запрещены:

8.3.5/4:

A cv-qualifier-seq shall only be part of the function type for a nonstatic member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type, i.e., it does not create a cv-qualified function type. In fact, if at any time in the determination of a type a cv-qualified function type is formed, the program is ill-formed.

У тебя аргумент для параметра Less выводится как тип функции. Соответственно, const Less получается const-квалифицированным типом функции. Это подпадает под 14.8.2/2 bullet 3/9

Type deduction may fail for the following reasons:
[...]
— Attempting to create a cv-qualified function type

Согласно, 14.8.3/1,

A function template can be overloaded either by (non-template) functions of its name or by (other) function templates of the same name. When a call to that name is written (explicitly, or implicitly using the operator notation), template argument deduction (14.8.2) and checking of any explicit template arguments (14.3) are performed for each function template to find the template argument values (if any) that can be used with that function template to instantiate a function template specialization that can be invoked with the call arguments. For each function template, if the argument deduction and checking succeeds, the template-arguments (deduced and/or explicit) are used to instantiate a single function template specialization which is added to the candidate functions set to be used in overload resolution. If, for a given function template, argument deduction fails, no such function is added to the set of candidate functions for that template. The complete set of candidate functions includes all the function templates instantiated in this way and all of the non-template overloaded functions of the same name. The function template specializations are treated like any other functions in the remainder of overload resolution, except as explicitly noted in 13.3.3.

твоя Sort должна быть исключена из множества кандидатов, и если других подходящих кандидатов на вызов нет, то программа является неправильно сформированной.

По правилам черновика C++0x WG21 — N3126 top-level cv-qualifier-ы типов функций просто игнорируются:

8.3.5/6:

A cv-qualifier-seq shall only be part of the function type for a non-static member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. [ Note: a function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. —end note ] The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored.

По этим новым правилам с выведением типа для твоего случая проблем уже нет (что, кстати, можно рассматривать как breaking changes).

Если есть ещё вопросы к ОВБПС, обращайся
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.