การใช้ Visual Studio 2008 กับเซอร์วิสแพ็ค tr1 และ Intel C++ Compiler 11.1.071 [IA-32] สิ่งนี้เกี่ยวข้องกับ คำถาม
ฉันกำลังพยายามเขียนแผนที่การทำงานสำหรับ c++ ซึ่งจะทำงานเหมือนกับเวอร์ชัน Ruby
strings = [2,4].map { |e| e.to_s }
ดังนั้นฉันจึงได้กำหนดฟังก์ชันต่อไปนี้ในเนมสเปซ VlcFunctional
template<typename Container, typename U>
vector<U> map(const Container& container, std::tr1::function<U(Container::value_type)> f)
{
vector<U> transformedValues(container.size());
int index = -1;
BOOST_FOREACH(const auto& element, container)
{
transformedValues.at(++index) = f(element);
}
return transformedValues;
}
และคุณสามารถเรียกสิ่งนี้ได้ (โปรดทราบว่าอาร์กิวเมนต์เทมเพลตฟังก์ชันถูกกำหนดไว้อย่างชัดเจน):
vector<int> test;
test.push_back(2); test.push_back(4);
vector<string> mappedData2 = VlcFunctional::map<vector<int>,string>(test, [](int i) -> string
{
return ToString(i);
});
หรือเป็นเช่นนั้น (โปรดทราบว่าอาร์กิวเมนต์เทมเพลตฟังก์ชันไม่ได้ถูกกำหนดไว้อย่างชัดเจน)
std::tr1::function f = [](int i) -> string { return ToString(i); };
vector<string> mappedData2 = VlcFunctional::map<vector<int>,string>(test, f);
แต่ที่สำคัญ ไม่ใช่แบบนี้
vector<string> mappedData2 = VlcFunctional::map(test, [](int i) -> string { return ToString(i); });
หากไม่มีคำจำกัดความที่ชัดเจนของอาร์กิวเมนต์เทมเพลต hte ก็จะไม่ทราบว่าควรใช้เทมเพลตใดและเกิดข้อผิดพลาดในการคอมไพล์
..\tests\VlcFunctional_test.cpp(106): error: no instance of function template "VlcFunctional::map" matches the argument list, argument types are: (std::vector<int, std::allocator<int>>, __lambda3)
การกำหนดอาร์กิวเมนต์ของเทมเพลตทำให้ไวยากรณ์มีขนาดใหญ่ขึ้นมาก และฉันกำลังมุ่งเป้าไปที่ไซต์การโทรที่มีปัญหาน้อยที่สุด มีแนวคิดใดบ้างที่ว่าทำไมจึงไม่รู้ว่าจะแปลงได้อย่างไร นี่เป็นปัญหาของคอมไพเลอร์หรือภาษาไม่อนุญาตให้มีการอนุมานอาร์กิวเมนต์เทมเพลตประเภทนี้
typename Container::value_type
ในการประกาศstd::tr1::function
Visual นั้นให้อภัยได้ แต่คอมไพเลอร์อื่นไม่ได้เป็นเช่นนั้น - person Matthieu M.   schedule 09.09.2010