Error: "2 overloads have similar conversions" - c++

EDIT: As I was writing the question I noticed that the method std::string GetNodeValue(const std::string& nodePath, const char * defaultValue) wasn't const. As LogicStuff also mentioned in his comment, adding the const qualification resolved the ambiguity.
I know this question was already been asked and answered properly here and several other times. I understand the underlying problem but I can't quite figure out why it is happening in this particular case and it has awoken my curious self.
I have the following class:
class ConfigurationReader
{
public:
// ...
std::string GetNodeValue(const std::string& nodePath, const char * defaultValue)
{
const std::string temp(defaultValue);
return GetNodeValue(nodePath, temp);
}
template <typename T> T GetNodeValue(const std::string & nodePath, T defaultValue) const
{
boost::optional<T> nodeValue = configuration.getNodeValueNothrow<T>(nodePath);
if ( nodeValue )
{
return *nodeValue;
}
LogConfigurationProblemsCri(logger, "Node not found: " << nodePath << ", Default value: " << defaultValue);
return defaultValue;
}
// ...
};
The template method has also several specializations for the types int16_t, uint16_t, and so on up to uint64_t.
It works like a charm when used:
string someValue = configurationReaderPtr->GetNodeValue("some_noe", "");
uint32_t otherValue = configurationReaderPtr->GetNodeValue("other_node", 11000);
bool yetAnother = configurationReaderPtr->GetNodeValue("other_node", true);
Except in one case:
uint32_t otherValue = configurationReaderPtr->GetNodeValue("other_node", 0);
The error I keep getting is:
"2 overloads have similar conversions
could be 'std::string ConfigurationReader::GetNodeValue(const std::string &,const char *)' or 'uint32_t ConfigurationReader::GetNodeValue(const std::string &,uint32_t) const'"
I tried casting the "default" value: uint32_t(0), static_cast<uint32_t>(0), 0U without any luck.
I should point out that I already found a workaround:
uint32_t otherValue = 0;
otherValue = configurationReaderPtr->GetNodeValue("other_node", otherValue);
But this doesn't answer my curiosity. I am currently using Microsoft Visual Studio 2012 Express and boost 1.54 libraries.
Any thoughts?

This is, because 0 is the literal for an empty pointer (which in modern C++ is replaced by "nullptr").
So 0 can be either an int or an empty pointer, especially a char*
Edit to add some reference:
You can find this in the standard as
4.10 Pointer conversions
A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t
(the last one is the reference to nullptr)

Both overloads are considered equally viable for
configurationReaderPtr->GetNodeValue("other_node", 0);
because:
requires an implicit conversion from 0, which is of type int to const char *.
requires an implicit conversion from ConfigurationReader* to ConfigurationReader const* (to call const-qualified member function)
After making both overloads (equally) const-qualified, the code compiles (the function template is preferred). The 1st overload also does not modify any members in the first place.
Live on Coliru

In your particular example, it seems prudent to change signature of string version to
std::string GetNodeValue(const std::string& nodePath, const std::string defaultValue)
This will remove any ambiguity.

Related

Getting a (const char*) representation of an integer in a one-liner

I'm working on a software using a home-made report library which takes only (const char *) type as an argument :
ReportInfo(const char* information);
ReportError(const char* error);
[...]
As I'm trying to report value of integers, I'd like to get a representation of those integers in a const char* type.
I can do it that way :
int value = 42;
string temp_value = to_string(value);
const char *final_value= temp_value.c_str();
ReportInfo(final_value);
It would be great if I could do it without instancing the temp_value.
I tried this :
int value = 42;
const char* final_value = to_string(value).c_str();
ReportInfo(final_value);
but final_value is equal to '\0' in that case.
Any idea how to do it ?
You could try
ReportInfo(to_string(value).c_str());
because the temporary will not be destroyed until ReportInfo returns.
to_string(value) returns a temporary, so in your second example its lifetime ends at the end of the expression. so you have dangling pointer.

C++: concatenate an enum to a std::string

So I'm trying to concatenate an enum to an std::string. For this I wrote the following code.
typedef enum { NODATATYPE = -1,
DATATYPEINT,
DATATYPEVARCHAR
} DATATYPE;
inline std::string operator+(std::string str, const DATATYPE dt){
static std::map<DATATYPE, std::string> map;
if (map.size() == 0){
#define INSERT_ELEMENT(e) map[e] = #e
INSERT_ELEMENT(NODATATYPE);
INSERT_ELEMENT(DATATYPEINT);
INSERT_ELEMENT(DATATYPEVARCHAR);
#undef INSERT_ELEMENT
}
return str + map[dt];
}
and
DATATYPE dt1 = DATATYPEINT;
std::string msg = "illegal type for operation" + dt1;
I'm getting the following warning compiling this code.
warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: std::string msg = "illegal type for operation" + dt1; absyn.cpp:642:55: note: candidate 1: operator+(const char*, long int)
In file included from file.cpp:4:0: file.h:18:20: note: candidate 2: std::string operator+(std::string, DATATYPE) inline std::string operator+(std::string str, const DATATYPE dt){
What does this warning exactly mean, and how to solve it?
What you pass to the operator is a const char* (to a string literal) and a DATATYPE. Since there is no overload operator+(const char*, DATATYPE), the compiler looks for overloads where the parameters can be implicitly converted. The candidates are in the warning:
operator+(const char*, long int)
operator+(std::string, DATATYPE)
The first parameter can be converted from const char* to std::string or the second parameter can be converted from DATATYPE to long int. So the first overload "wins" the overload resolution on the basis of first parameter and the second overload "wins" on the basis of the second argument. Since there is no overload that "wins" the resolution on the basis of both arguments, they are ambiguous.
The compiler warns you because it suspects that it may have chosen different overload than what you meant to call. If you compile with -pedantic on gcc you'll get error: ambiguous overload for... instead of just a warning.
The solution is to disambiguate the call by passing parameters of types that match exactly. A simple way would be:
std::string msg = std::string("illegal type for operation") + dt1;
or nicer in c++14
std::string msg = "illegal type for operation"s + dt1;

Overload char pointers and string literals

I'm trying to create a class that will accept (and can disambiguate) string literals from char pointers. When searching this problem the solution provided was to create a 'holder' class that only accepts char pointers:
template< typename char_t >
class String
{
struct holder_t
{
const char_t* s;
holder_t( const char_t* s ) : s(s) {}
holder_t( char_t* s ) : s(s) {}
};
public:
// Construct from string literal
template< size_t S >
String( const char_t (&str)[S] )
{
std::cout << "String Literal: " << str;
}
// Construct from char pointer
String( holder_t h )
{
std::cout << "Char Pointer: " << h.s;
}
};
The big idea is that you should never have to explicitly create instances of this class, it should happen by implicit conversion:
void StringFoo( String<char> s )
{
}
However this results in compile errors for char pointers, why isn't the implicit conversion working?
int main()
{
// Works!
StringFoo( "literal" );
// error C2664: 'StringFoo' : cannot convert parameter 1 from 'const char *' to 'String<char_t>'
// with [ char_t=char ]
// No constructor could take the source type, or constructor overload resolution was ambiguous
StringFoo( (const char*)"const char ptr" );
// Works!
StringFoo( String<char>((const char*)"const char ptr") );
// error C2664: 'StringFoo' : cannot convert parameter 1 from 'char *' to 'String<char_t>'
// with [ char_t=char ]
// No constructor could take the source type, or constructor overload resolution was ambiguous
StringFoo( (char*)"char ptr" );
// Works!
StringFoo( String<char>((char*)"const char ptr") );
return 0;
}
This is just a simple pointless example; in my real code I created a class that will hold the hash of the string.
The hash should be generated at compile time if a string literal is passed and calculated at runtime if a char pointer is passed.
However this should be completely transparent to the user who just passes strings around, hashing is done automagically.
The reason the code doesn't work with pointer is that it requires two versions (char const* to holder and holder to String. However, implicit conversions will do at most one conversion.
For the purpose you are describing I'd think you can reasonably just distinguish between char const(&)[N] and char const*: since you always want to compute a hash anyway and just make it is a constexpr where possible, making the version taking char const(&)[N] a reference should do the trick.
To get from a string literal to a String requires two user-defined conversions - one to holder_t and another to String. But overload resolution only allows you to have one such conversion per argument.

Restrict passed parameter to a string literal

I have a class to wrap string literals and calculate the size at compile time.
The constructor looks like this:
template< std::size_t N >
Literal( const char (&literal)[N] );
// used like this
Literal greet( "Hello World!" );
printf( "%s, length: %d", greet.c_str(), greet.size() );
There is problem with the code however. The following code compiles and I would like to make it an error.
char broke[] = { 'a', 'b', 'c' };
Literal l( broke );
Is there a way to restrict the constructor so that it only accepts c string literals? Compile time detection is preferred, but runtime is acceptable if there is no better way.
There is a way to force a string literal argument: make a user defined literal operator. You can make the operator constexpr to get the size at compile time:
constexpr Literal operator "" _suffix(char const* str, size_t len) {
return Literal(chars, len);
}
I don't know of any compiler that implements this feature at this time.
Yes. You can generate compile time error with following preprocessor:
#define IS_STRING_LITERAL(X) "" X ""
If you try to pass anything other than a string literal, the compilation will fail. Usage:
Literal greet(IS_STRING_LITERAL("Hello World!")); // ok
Literal greet(IS_STRING_LITERAL(broke)); // error
With a C++11 compiler with full support for constexpr we can use a constexpr constructor using a constexpr function, which compiles to a non-const expression body in case the trailing zero character precondition is not fulfilled, causing the compilation to fail with an error. The following code expands the code of UncleBens and is inspired by an article of Andrzej's C++ blog:
#include <cstdlib>
class Literal
{
public:
template <std::size_t N> constexpr
Literal(const char (&str)[N])
: mStr(str),
mLength(checkForTrailingZeroAndGetLength(str[N - 1], N))
{
}
template <std::size_t N> Literal(char (&str)[N]) = delete;
private:
const char* mStr;
std::size_t mLength;
struct Not_a_CString_Exception{};
constexpr static
std::size_t checkForTrailingZeroAndGetLength(char ch, std::size_t sz)
{
return (ch) ? throw Not_a_CString_Exception() : (sz - 1);
}
};
constexpr char broke[] = { 'a', 'b', 'c' };
//constexpr Literal lit = (broke); // causes compile time error
constexpr Literal bla = "bla"; // constructed at compile time
I tested this code with gcc 4.8.2. Compilation with MS Visual C++ 2013 CTP failed, as it still does not fully support constexpr (constexpr member functions still not supported).
Probably I should mention, that my first (and preferred) approach was to simply insert
static_assert(str[N - 1] == '\0', "Not a C string.")
in the constructor body. It failed with a compilation error and it seems, that constexpr constructors must have an empty body. I don't know, if this is a C++11 restriction and if it might be relaxed by future standards.
No there is no way to do this. String literals have a particular type and all method overload resolution is done on that type, not that it's a string literal. Any method which accepts a string literal will end up accepting any value which has the same type.
If your function absolutely depends on an item being a string literal to function then you probably need to revisit the function. It's depending on data it can't guarantee.
A string literal does not have a separate type to distinguish it from a const char array.
This, however, will make it slightly harder to accidentally pass (non-const) char arrays.
#include <cstdlib>
struct Literal
{
template< std::size_t N >
Literal( const char (&literal)[N] ){}
template< std::size_t N >
Literal( char (&literal)[N] ) = delete;
};
int main()
{
Literal greet( "Hello World!" );
char a[] = "Hello world";
Literal broke(a); //fails
}
As to runtime checking, the only problem with a non-literal is that it may not be null-terminated? As you know the size of the array, you can loop over it (preferable backwards) to see if there's a \0 in it.
I once came up with a C++98 version that uses an approach similar to the one proposed by #k.st. I'll add this for the sake of completeness to address some of the critique wrt the C++98 macro.
This version tries to enforce good behavior by preventing direct construction via a private ctor and moving the only accessible factory function into a detail namespace which in turn is used by the "offical" creation macro. Not exactly pretty, but a bit more fool proof. This way, users have to at least explicitly use functionality that is obviously marked as internal if they want to misbehave. As always, there is no way to protect against intentional malignity.
class StringLiteral
{
private:
// Direct usage is forbidden. Use STRING_LITERAL() macro instead.
friend StringLiteral detail::CreateStringLiteral(const char* str);
explicit StringLiteral(const char* str) : m_string(str)
{}
public:
operator const char*() const { return m_string; }
private:
const char* m_string;
};
namespace detail {
StringLiteral CreateStringLiteral(const char* str)
{
return StringLiteral(str);
}
} // namespace detail
#define STRING_LITERAL_INTERNAL(a, b) detail::CreateStringLiteral(a##b)
/**
* \brief The only way to create a \ref StringLiteral "StringLiteral" object.
* This will not compile if used with anything that is not a string literal.
*/
#define STRING_LITERAL(str) STRING_LITERAL_INTERNAL(str, "")

C++ deprecated conversion from string constant to 'char*'

I have a class with a private char str[256];
and for it I have an explicit constructor:
explicit myClass(char *func)
{
strcpy(str,func);
}
I call it as:
myClass obj("example");
When I compile this I get the following warning:
deprecated conversion from string constant to 'char*'
Why is this happening?
This is an error message you see whenever you have a situation like the following:
char* pointer_to_nonconst = "string literal";
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.
So, somewhere you are missing one or more consts in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.
The warning:
deprecated conversion from string constant to 'char*'
is given because you are doing somewhere (not in the code you posted) something like:
void foo(char* str);
foo("hello");
The problem is that you are trying to convert a string literal (with type const char[]) to char*.
You can convert a const char[] to const char* because the array decays to the pointer, but what you are doing is making a mutable a constant.
This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string constant to (char *).
There are 3 solutions:
Solution 1:
const char *x = "foo bar";
Solution 2:
char *x = (char *)"foo bar";
Solution 3:
char* x = (char*) malloc(strlen("foo bar")+1); // +1 for the terminator
strcpy(x,"foo bar");
Arrays also can be used instead of pointers because an array is already a constant pointer.
Update: See the comments for security concerns regarding solution 3.
A reason for this problem (which is even harder to detect than the issue with char* str = "some string" - which others have explained) is when you are using constexpr.
constexpr char* str = "some string";
It seems that it would behave similar to const char* str, and so would not cause a warning, as it occurs before char*, but it instead behaves as char* const str.
Details
Constant pointer, and pointer to a constant. The difference between const char* str, and char* const str can be explained as follows.
const char* str : Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
str++ ; : VALID. We are modifying the pointer, and not the data being pointed to.
*str = 'a'; : INVALID. We are trying to modify the data being pointed to.
char* const str : Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
*str = 'a'; : VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];.
const char* const str : Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
*str = 'a'; : INVALID. We are trying to modify the data pointed by this pointer, which is also constant.
In my case the issue was that I was expecting constexpr char* str to behave as const char* str, and not char* const str, since visually it seems closer to the former.
Also, the warning generated for constexpr char* str = "some string" is slightly different from char* str = "some string".
Compiler warning for constexpr char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *const'
Compiler warning for char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *'.
Tip
You can use C gibberish ↔ English converter to convert C declarations to easily understandable English statements, and vice versa. This is a C only tool, and thus wont support things (like constexpr) which are exclusive to C++.
In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
Maybe you can try this:
void foo(const char* str)
{
// Do something
}
foo("Hello")
It works for me
I solve this problem by adding this macro in the beginning of the code, somewhere. Or add it in <iostream>, hehe.
#define C_TEXT( text ) ((char*)std::string( text ).c_str())
I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.
For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to char *:
class StringWrapper {
std::vector<char> vec;
public:
StringWrapper(const std::string &str) : vec(str.begin(), str.end()) {
}
char *getChars() {
return &vec[0];
}
};
The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):
#include <iostream>
void Swap(const char * & left, const char * & right) {
const char *const temp = left;
left = right;
right = temp;
}
int main() {
const char * x = "Hello"; // These works because you are making a variable
const char * y = "World"; // pointer to a constant string
std::cout << "x = " << x << ", y = " << y << '\n';
Swap(x, y);
std::cout << "x = " << x << ", y = " << y << '\n';
}