मेरे पास वर्तमान में map<int, std::wstring>
है, लेकिन लचीलापन के लिए, मैं एक लैम्ब्डा अभिव्यक्ति असाइन करने में सक्षम होना चाहता हूं, std::wstring
को मानचित्र में मान के रूप में लौटाना चाहता हूं।std :: टेम्पलेट पैरामीटर के रूप में कार्य
template <typename T>
class ValueOrFunction
{
private:
std::function<T()> m_func;
public:
ValueOrFunction() : m_func(std::function<T()>()) {}
ValueOrFunction(std::function<T()> func) : m_func(func) {}
T operator()() { return m_func(); }
ValueOrFunction& operator= (const T& other)
{
m_func = [other]() -> T { return other; };
return *this;
}
};
और यह पसंद का उपयोग करें::
तो मैं इस टेम्पलेट श्रेणी का निर्माण
typedef ValueOrFunction<std::wstring> ConfigurationValue;
std::map<int, ConfigurationValue> mymap;
mymap[123] = ConfigurationValue([]() -> std::wstring { return L"test"; });
mymap[124] = L"blablabla";
std::wcout << mymap[123]().c_str() << std::endl; // outputs "test"
std::wcout << mymap[124]().c_str() << std::endl; // outputs "blablabla"
अब, मैं लैम्ब्डा लपेटकर के लिए निर्माता का उपयोग नहीं करना चाहते हैं, तो मैं करने का निर्णय लिया एक दूसरे असाइनमेंट ऑपरेटर std::function
के लिए इस समय जोड़ने के लिए,:
ValueOrFunction& operator= (const std::function<T()>& other)
{
m_func = other;
return *this;
}
इस poi है एनटी जहां संकलक शिकायत शुरू करता है। लाइन mymap[124] = L"blablabla";
अचानक इस त्रुटि में परिणाम है:
error C2593: 'operator = is ambiguous'
IntelliSense कुछ अधिक जानकारी देता है:
more than one operator "=" matches these operands: function "ValueOrFunction::operator=(const std::function &other) [with T=std::wstring]" function "ValueOrFunction::operator=(const T &other) [with T=std::wstring]" operand types are: ConfigurationValue = const wchar_t [10] c:\projects\beta\CppTest\CppTest\CppTest.cpp 37 13 CppTest
तो, मेरे सवाल का, यही वजह है कि संकलक std::function<T()>
और T
के बीच भेद करने में सक्षम नहीं है? और मैं इसे कैसे ठीक कर सकता हूं?
इसे देखें [यहां] (http://ideone.com/XpOXMF) –
मैं सोच रहा था कि क्या SFINAE समझ में आएगा, और मैंने इसे अत्यधिक जटिल के रूप में सुझाव देने का विकल्प नहीं चुना। अभ्यास के रूप में टैग प्रेषण यहां एक अच्छा साफ समाधान +1 है (हालांकि यह अधिक योग्य है) –