สำหรับคำถามแรก:
ฉันต้องการเขียนฟังก์ชันเพื่อเชื่อมสตริงเข้าด้วยกัน และฟังก์ชันสามารถรับได้หลายสตริง
#include <string>
#include <vector>
#include <type_traits>
template <class... Args, typename std::enable_if<std::is_same<typename std::decay<Args...>::type, std::string>::type>::type>
std::string foo(const std::string &first, const Args &... senconds) {
std::string delimiter = "$$";
std::string ret = first;
std::vector<std::string> vec{senconds...};
for (auto second = vec.rbegin(); second != vec.rend(); second++) {
ret = delimiter + *second + delimiter + ret;
}
return ret;
}
แต่เมื่อฉันเรียกใช้มันเช่น:
std::string name = "x";
name = foo(name, "xxx");
คอมไพเลอร์จะเกิดข้อผิดพลาด:
error: no matching function for call to ‘foo(std::__cxx11::string&, const char [4])’
และจะมีข้อความว่า
note: couldn't deduce template parameter ‘<anonymous>’
ฉันคิดว่าฉันควรแก้ไขข้อจำกัดในเทมเพลต และฉันได้ลองวิธีการที่เกี่ยวข้องทั้งหมดใน type_traits
แล้ว แต่ก็ไม่ได้ผลเลย
สำหรับคำถามที่สอง:
ฉันต้องการซ่อนการใช้งานฟังก์ชันบางอย่าง แต่สำหรับฟังก์ชันเทมเพลต ไม่สามารถใส่คำจำกัดความใน .hpp
ได้ และใส่การใช้งานใน .cpp
คอมไพเลอร์จะส่งข้อผิดพลาด undefined reference
มีวิธีที่สง่างามในการแก้ปัญหานี้หรือไม่?
ขอบคุณ.
Args...
ให้เป็นstd::string
เพียงบางสิ่งที่คุณสามารถยกตัวอย่างstd::string
ด้วย - person Caleth   schedule 28.11.2019