I write a class with template method and use it like below.
#include<string> using namespace std; class A { public: template<typename T> void DoSomething(uint32_t index, T arg); }; template<> void A::DoSomething(uint32_t index,const string &arg) { } void Run(A &a, const string &str) { a.DoSomething(0, str); a.DoSomething<const string &>(0, str); } int main() { A a; Run(a, "HelloWorld"); return 0; } This code failed with linker error : undefined reference to `void A::DoSomething<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >(unsigned int, std::__cxx11::basic_string<char, std::char_traits, std::allocator >)
So compiler discards the const reference qualifiers.
Why this happens ? How can fix it ?
Tis deduced tostringin the first example. In general, a by-value parameter will never deduce to a reference. If you want that, the parameter should beconst T &, notT.const T &andT &&. The first one copies non-persistent objects, the second onestd::moves them. For persistent objects, the first one remembers the address, and the other fails with an exceptions.