Problem With Overloading A Function For Literal Strings
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?
Answer
Note that "test2"
literal is an lvalue, while char *&&x
is an rvalue reference and cannot be bound to an lvalue.
Related Questions
- → Comparing two large files are taking over four hours
- → Setting JSON node name to variable value
- → Compiling GLUT using Emscripten
- → Evaluate check box from a scanned image in node.js
- → Find an easy web server framework for mobile game
- → my https C++ code doesn't work on some sites (binance)
- → Error while opening pivx wallet on ubuntu
- → Why sending a POST by AJAX is interpreted by the HTTP Server as OPTIONS and sending by CURL is effectively a PUT?
- → Python reading in one line multiple types for a calculator
- → How do I properly pass an argument to a function
- → Accessing Websql database with Qt
- → Using Mysql C API for c++ codes
- → How do I set constants at run-time in a c++ header file, imported through Cython?