In questo answer ho dato, ha avuto senso utilizzare this
e l'attributo della classe _arg
nel tipo di ritorno finale come parte dell'espressione decltype
. Si può fare a meno, ma è scomodo.Utilizzando questo e gli attributi nella funzione membro trailing tipi di ritorno?
Né clang 3.0 (vedere di seguito) né gcc 4.5.2 tuttavia accettato.
#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 dice:
$ 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.
Hum ... non così grande.
Tuttavia, il supporto di C++ 11 è hacky nella migliore delle ipotesi nella maggior parte dei compilatori e non sono riuscito a trovare restrizioni specifiche menzionate nello standard (n3290).
Nei commenti, Xeo suggerito che avrebbe potuto essere un difetto nel standard ...
Quindi, è questo permessi o meno?
Bonus: e le versioni più recenti di clang/gcc supportano questo?
Clang 3.1 HEAD rilascia gli stessi errori. – Xeo
Errori simili su GCC 4.7. –
Btw, ho appena trovato [questa interessante domanda simile] (http://stackoverflow.com/q/7255379/500104). Inoltre, con il suggerimento di @Johannes di dichiarare il membro in anticipo, ricevo solo un errore su "this" nel tipo di ritorno finale, non più su "_arg" con Clang 3.1 HEAD. – Xeo