【发布时间】:2014-01-03 22:52:35
【问题描述】:
我目前有一个map<int, std::wstring>,但为了灵活性,我希望能够分配一个 lambda 表达式,将 std::wstring 作为映射中的值返回。
所以我创建了这个模板类:
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"
现在,我不想使用构造函数来包装 lambda,所以我决定添加第二个赋值运算符,这次是 std::function:
ValueOrFunction& operator= (const std::function<T()>& other)
{
m_func = other;
return *this;
}
这是编译器开始抱怨的地方。 mymap[124] = L"blablabla";这行突然出现这个错误:
错误 C2593:“运算符 = 不明确”
IntelliSense 提供了更多信息:
多个运算符“=”匹配这些操作数:函数 "ValueOrFunction::operator=(const std::function &other) [with T=std::wstring]" 函数 "ValueOrFunction::operator=(const T &other) [with T=std::wstring]" 操作数类型为:ConfigurationValue = 常量 wchar_t [10] c:\projects\beta\CppTest\CppTest\CppTest.cpp 37 13 CppTest
那么,我的问题是,为什么编译器不能区分std::function<T()> 和T?我该如何解决这个问题?
【问题讨论】:
标签: c++ templates c++11 std-function