इस answer में मैंने this
का उपयोग करने के लिए और decltype
अभिव्यक्ति के भाग के रूप में पिछली वापसी प्रकार में _arg
की विशेषता का उपयोग करने के लिए समझ में आया। बिना करना, लेकिन असुविधाजनक करना संभव है।इसका उपयोग और सदस्य फ़ंक्शन पीछे वापसी प्रकारों में विशेषताएँ?
न तो क्लैंग 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";
}
बजना 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.
हम ... इतना महान नहीं।
हालांकि, सी ++ 11 का समर्थन अधिकांश कंपाइलरों में सबसे अच्छा हैकी और मुझे मानक (एन 32 9 0) में निर्दिष्ट विशिष्ट प्रतिबंध नहीं मिल सका।
टिप्पणियों में, Xeo सुझाव दिया कि यह मानक में एक दोष हो सकता है ...
तो, यह अनुमति नहीं है?
बोनस: और क्लैंग/जीसीसी के अधिक हाल के संस्करणों का समर्थन करते हैं?
क्लैंग 3.1 HEAD एक ही त्रुटि को हल करता है। – Xeo
जीसीसी 4.7 पर इसी तरह की त्रुटियां। –
बीटीडब्ल्यू, मैंने अभी पाया [यह दिलचस्प, समान प्रश्न] (http://stackoverflow.com/q/7255379/500104)। इसके अलावा, सदस्य को आगे घोषित करने के @ जोहान्स के सुझाव के साथ, मुझे क्लैंग 3.1 हेड के साथ अब '_arg' के बारे में नहीं, पीछे वापसी प्रकार में' this' के बारे में एक त्रुटि मिलती है। – Xeo