I have a template function that handles rvalues arguments. The argument is supposed to expose a certian function. For those rvalues that do not have this function, I need to use template specialization to handle the exceptions. The problem I have is with string literals. Here's a short example of what I am trying to do.
#include <iostream>
#include <string>
using namespace std;
struct A
{
template < class T > void foo (T && x)
{
x.baa();
}
};
struct B{
void baa(){
cout << "I have baa()" << endl;
};
};
template <> void
A::foo (std::string && x)
{
cout << "I am a std::string, I don't have baa()" << endl;
};
template <> void
A::foo (char *&&x)
{
cout << "I am a char* and I am sad because nobody ever calls me" << endl;
};
int
main ()
{
A a;
a.foo (B());
a.foo (std::string ("test1"));
a.foo ("test2"); // this line causes a compiler error
return 0;
}
If I try to compile the snippet above, I get the following error
main.cpp:16:7: error: request for member ‘baa’ in ‘x’, which is of non-class type ‘const char [6]’
16 | x.baa();
Obviously the compiler is trying to apply the generic function rather than the specialization for char*. How can I write a specialization that captures literal strings of any length?
CodePudding user response:
Note that "test2" literal is an lvalue, while char *&&x is an rvalue reference and cannot be bound to an lvalue.
