Tôi hiện có map<int, std::wstring>
, nhưng để linh hoạt, tôi muốn có thể gán một biểu thức lambda, trả về std::wstring
làm giá trị trong bản đồ.std :: function như tham số mẫu
Vì vậy, tôi đã tạo biểu mẫu này lớp:
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;
}
};
và sử dụng nó như:
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"
Bây giờ, tôi không muốn sử dụng các nhà xây dựng cho gói các lambda, vì vậy tôi quyết định thêm toán tử gán thứ hai, lần này cho số std::function
:
ValueOrFunction& operator= (const std::function<T()>& other)
{
m_func = other;
return *this;
}
Đây là poi nt nơi trình biên dịch bắt đầu phàn nàn. Dòng mymap[124] = L"blablabla";
đột nhiên dẫn đến lỗi này:
error C2593: 'operator = is ambiguous'
IntelliSense đưa ra một số thông tin thêm:
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
Vì vậy, câu hỏi của tôi là, tại sao không phải là trình biên dịch có thể phân biệt giữa std::function<T()>
và T
? Và làm thế nào tôi có thể sửa lỗi này?
Xem nó hoạt động [ở đây] (http://ideone.com/XpOXMF) –
Tôi đã suy nghĩ xem liệu SFINAE có hợp lý hay không và tôi đã chọn không đề xuất nó quá phức tạp. Việc gửi thẻ như được thực hiện ở đây là một giải pháp sạch tốt +1 (mặc dù nó xứng đáng hơn) –