В этом ответе , который я дал, имело смысл использовать this
и атрибут класса _arg
в конце типа возврата как часть выражения decltype
. Можно обойтись без, но неудобно.
Ни clang 3.0 (см. Ниже), ни gcc 4.5.2 не приняли его.
#include <iostream>
class MyClass {
public:
MyClass(int i): _arg(i) {}
template <typename F>
auto apply(F& f) -> decltype(f(_arg)) {
return f(_arg);
}
template <typename F>
auto apply(F& f) -> decltype(f(*this, _arg)) {
return f(*this, _arg);
}
private:
int _arg;
};
struct Id {
template <typename V>
V operator()(V v) const { return v; }
};
struct ComplexId {
template <typename C, typename V>
V operator()(C const&, V v) { return v + 1; }
};
int main() {
Id id; ComplexId complex;
MyClass c(0);
std::cout << c.apply(id) << " " << c.apply(complex) << "\n";
}
Clang 3.0 говорит:
$ clang++ -std=c++11 -Weverything test.cpp
test.cpp:8:38: error: use of undeclared identifier '_arg'
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:8:45: error: type name requires a specifier or qualifier
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:8:45: error: C++ requires a type specifier for all declarations
auto apply(F& f) -> decltype(f(_arg)) {
~~~~~~~~ ^
test.cpp:8:7: error: 'auto' return without trailing return type
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:13:39: error: invalid use of 'this' outside of a nonstatic member function
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
test.cpp:13:52: error: type name requires a specifier or qualifier
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
test.cpp:13:52: error: C++ requires a type specifier for all declarations
auto apply(F& f) -> decltype(f(*this, _arg)) {
~~~~~~~~ ^
test.cpp:13:7: error: 'auto' return without trailing return type
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
8 errors generated.
Хм ... не так здорово.
Однако поддержка C ++ 11 в лучшем случае хакерская в большинстве компиляторов, и я не смог найти конкретных ограничений, упомянутых в Стандарте (n3290).
В комментариях Xeo предположил, что это могло быть дефектом в Стандарте ...
Итак, это разрешено или нет?
Бонус: а более поздние версии clang / gcc поддерживают это?