I'm trying to call a nonmember function of a derived class from a base class, but getting this error:
error: no matching function for call to 'generate_vectorlist(const char&)'
Here's the relevant code snippets from the base class:
//Element.cpp
#include "Vector.h"
...
string outfile;
cin >> outfile;
const char* outfile_name = outfile.c_str();
generate_vectorlist(*outfile_name); //ERROR
...
and the derived class (this is a template class, so everything's in the header):
//Vector.h
template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )
{
std::ofstream vectorlist(outfile_name);
if (vectorlist.is_open())
for (Element::vciter iter = Element::vectors.begin(); iter!=Element::vectors.end(); iter++)
{
Vector<T>* a = new Vector<T>(*iter);
vectorlist << a->getx() << '\t' << a->gety() << '\t'<< a->getz() << std::endl;
delete a;
}
else { std::cout << outfile_name << " cannot be opened." << std::endl;}
vectorlist.close();
}
My guess is there's just a small syntax thing that I'm missing. Any ideas?
You're dereferencing the pointer so you're passing a const char, not a const char*.
try this:
generate_vectorlist(outfile_name);
You have two problems:
generate_vectorlist takes a const char *, not a const char &.
The template type is not in the function signature so the compiler can not deduce the type therefore you need to specify it (using int in my example).
So you need to do:
generate_vectorlist<int>(outfile_name);
In the first bit, try:
generate_vectorlist(outfile_name);
You should be passing a character pointer, not a character.
You need to specify the template argument. There's nothing the compiler can use to deduce what type T is. So you'll have to call it like generate_vectorlist<MyType>(outfile_name);, using the appropriate type for MyType.
This is the problem:
template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )
The compiler can't deduce the type of T, so it has no idea which generate_vectorlist to use.
Call it like this:
generate_vectorlist<vectortype>(outfile_name);
Though I would actually suggest that this code doesn't make any sense in the first place.
Related
From here: Difference between 'struct' and 'typedef struct' in C++?, I found I need class identifier if there is name collision (for example if class name is the same as function name):
#include <iostream>
using namespace std;
class foo
{
public:
foo() {}
operator char const *() const
{
return "class";
}
};
char const *foo()
{
return "function\n";
}
int main()
{
char const *p;
p = class foo(); //this gets error
cout << p << '\n';
return 0;
}
output:
error: expected primary-expression before ‘class’
p = class foo();
What is primary expression here and how can I identify the class instead of the function? I would like it to print class instead of function. How to do so?
One of the possible solutions:
using bar = class foo;
p = bar();
int main()
{
char const *p;
struct foo f;
p = static_cast<char const*>(f);
cout << p << '\n';
return 0;
}
By the way, the answer you link mentions that one can use typedef class foo foo; to trigger a compiler error for a function of same name. Havning a class and a function of same name isn't something desirable, but rather you need to workaround a bit the fact that the language allows it. And don't miss the last paragraph:
I can't imagine why anyone would ever want to hide a class name with a
function or object name in the same scope as the class. The hiding
rules in C were a mistake, and they should not have been extended to
classes in C++. Indeed, you can correct the mistake, but it requires
extra programming discipline and effort that should not be necessary.
If you are in control of either the function or the class you should definitely rename it or place it inside a namespace.
I found two solutions that are accepted by both g++ and clang. I do not know, however, if they are standard C++.
Uniform initialization
cout << (class foo){} << "\n";
Using a helper
template <typename T, typename ...Args>
T ctor(Args&& ...args) {
return T{ std::forward<Args>(args) ... };
}
// ...
cout << ctor<class foo>() << "\n";
I have a template class defined below. I pass the struct to a function like this:
Function call
function({2, 2})
Function declaration
void function(UnsignedVector2D pad) {
//get `pad` as a string so that I can write it to file
}
My question is - I want to keep a record on the vales of pad that are passed to the function. Is there a way inside the function that I can convert pad to a string for example {2,2} so that I can write it to a file? I can't extend the function declaration to pass other arguments but could write a toString() function perhaps. Is this possible?
template <class T>
struct Vector2D
{
T e0;
T e1;
};
using "UnsignedVector2D = Vector2D<unsigned_type>;
what I meant was how could I write a toString() method?
You can use an std::ostringstream for. You then can create the string as if you were using std::cout, below an example for a classic vector:
template <typename T>
std::string toString(std::vector<T> const& v)
{
std::ostringstream s;
s << "[ "
for(auto& t : v)
{
s << t << ", ";
}
s << ']';
return s.str(); // don't return by reference, would be a temporary!
}
Adjust to whatever meets your own needs (accepted data type, formatting, ...).
Editted - please skip to the edit, which has the real problem
I frequently run into situations in my string helper library of stand-alone functions, where I provide overloads of a function with versions that take a char and versions that take a std::string.
The problem is, the overload then becomes ambiguous when passed a string literal (const char*).
Example:
void myFunc(const std::string &subStr);
void myFunc(char character);
These two functions are implemented differently, one optimized for strings and one for a single char.
Howsoever, trying to call myFunc("literal") results in ambiguity, despite me always wanting it to call the std::string version.
This forces me to provide void myFunc(const char *str) versions of my overloads, which only are stubs like:
void myFunc(const char *str)
{
myFunc(std::string(str));
}
Is there some way to make these stub functions unnecessary? I'd like to just be able to make void myFunc(char c) 'explicit', but you can't make non-constructor non-member functions explicit. Which would solve the problem instantly. =(...
(As an aside, why can't you make standalone functions explicit?)
Edit:
You know what they say about programmers coding too late into the night! (If you remember the joke, tell me, because I was too sleepy when I originally heard it and I've since forgotten it)
The real problem
I'm using MinGW v4.7.2, and the problem was alot different then my post originally assumed.
The problem is, I have several overloads. Yes, this example works fine:
void myFunc(const std::string &subStr);
void myFunc(char character);
But if you add an std::function overload, it breaks down:
void myFunc(const std::string &subStr);
//Not actually part of the problem; I was confused by part of the error message highlighting this function.
//void myFunc(char character);
void myFunc(std::function<bool(char)); //<-- The real problem
My string library has std::string, char, and std::function overloads (and occasionally a few more overloads for simplifying functions with alot of optional parameters).
When I have std::function as an overload, I get this error message:
error: call of overloaded ‘myFunc(const char [15])’ is ambiguous
candidates are:
void myFunc(char) <near match>
no known conversion for argument 1 from ‘const char [15]’ to ‘char’
void myFunc(std::function<bool(char)>)
void myFunc(const string&)
The myFunc(char) was how I initially got confused last night. Removing that overload from the code, I get the error message:
error: call of overloaded ‘myFunc(const char [15])’ is ambiguous
candidates are:
void myFunc(std::function<bool(char)>)
void myFunc(const string&)
Here's a self-contained compilable example.
How can I make a string literal choose the std::string over the std::function?
It's probably ambiguous because std::function's constructor is templated and is designed to take a function pointer, among other things.
Since my string library, specifically, uses only std::function<bool(char)> and std::function<bool(const std::string&)>, already typedef'd, I could inherit those into a class with an explicit constructor.
Is there other suggestions or options available?
Can you update your compiler? Your example compiles as expected in g++4.8 and above.
This is actually is a current defect report in the C++ standard. See 2132. std::function ambiguity. It is currently in review status, but most likely will be accepted. This will make sure that non-Callable types like your example never participate in overload resolution:
These constructors shall not participate in overload resolution unless
f is Callable
Currently g++4.8 and above implements this.
You did not provide self-contained repro so it's hard to say what's wrong.
But here are a couple of guesses:
You have a bug in compiler (unlikely)
You don't call character overload properly. You should call it like that: myFunc('c').
You provided incorrect calling code or incorrect method signature(s).
I guess following code snippet should explain what should be happening and how to declare and call methods properly. Note myOtherFunc trick with capturing literal. It can be done better w/o template function, with smart wrapper around string, but I'll leave that out.
You can also try it on your compiler and see if it works, then we'll know if you have compiler problem.
Live code: http://codepad.org/gzB7xWs2
#include <string>
#include <iostream>
using namespace std;
void myFunc(char c) {
cout << "myFunc called with char" << endl;
}
void myFunc(const string& s) {
cout << "myFunc called with string" << endl;
}
void myOtherFunc(char c) {
cout << "myOtherFunc called with char" << endl;
}
void myOtherFunc(const string& s) {
cout << "myOtherFunc called with string" << endl;
}
template <size_t StingSizeWithNullTerminator>
void myOtherFunc(const char (&buf)[StingSizeWithNullTerminator]){
cout << "myOtherFunc called with literal of size " << (StingSizeWithNullTerminator - 1) << endl;
}
int main() {
myFunc("string");
myFunc('c');
myFunc(string("std string"));
myOtherFunc("string");
myOtherFunc('c');
myOtherFunc(string("string"));
return 0;
}
Output:
myFunc called with string
myFunc called with char
myFunc called with string
myOtherFunc called with literal of size 6
myOtherFunc called with char
myOtherFunc called with string
Update
Now, with the example, it's clear what the problem is.
The problem is that there is no method with exact signature that accepts char[15]. And compiler needs to perform conversion.
The problem is that it can either convert to std::string or to std::function (because std::function has template constructor which accepts any type, including char[15]). Therefore it can't choose which conversion to use and gives up.
Therefore there's no clean solution for that as far as I know of, but here are some no-so-clean:
Use explicit conversion to std::string when calling methods
Ask yourself (and maybe tell us), what's the reason for having myFunc which accepts both strings and functions. Maybe there's a problem with design and you can avoid having functions with same names.
If you only need to accept bool(&)(char) function, you can use custom wrapper instead (see example below)
Example for 3rd option (http://ideone.com/o0NqUf):
#include <iostream>
#include <functional> //Required for std::function.
struct Callback
{
Callback(bool (&func)(char)): m_func(func)
{}
bool operator()(char c) { return m_func(c); }
bool (&m_func)(char);
};
void myFunc(Callback seperatorFunc)
{
std::cout << "Callback overload" << std::endl;
}
void myFunc(const std::string &separator)
{
std::cout << "std::string overload" << std::endl;
}
bool testCallback(char)
{
return true;
}
int main()
{
myFunc("String literal");
myFunc(std::string("std::string"));
myFunc(testCallback);
return 0;
}
Output:
std::string overload
std::string overload
Callback overload
You should be able to SFINAE yourself very easily out of this one:
template <typename F>
auto myFunc(F f) -> decltype(!f('0'), std::function<bool(char)>(f), void()) {
std::cout << "std::function<bool(char)> overload" << std::endl;
}
Or, using a C++03 compiler (possibly using tr2/type_traits or Boost Type Traits if your compiler doesn't yet have them):
template <typename F>
void myFunc(F f, typename std::enable_if<std::is_constructible<
std::function<bool(char)>, F>::value>::type* = nullptr)
{
std::cout << "std::function<bool(char)> overload" << std::endl;
}
Proof it works:http://ideone.com/Q87JsV
#include <iostream>
#include <type_traits>
#include <functional>
#if 1
template <typename F>
auto myFunc(F f) -> decltype(!f('0'), std::function<bool(char)>(f), void()) {
std::cout << "std::function<bool(char)> overload" << std::endl;
}
#else
template <typename F>
void myFunc(F f, typename std::enable_if<std::is_constructible<
std::function<bool(char)>, F>::value>::type* = nullptr)
{
std::cout << "std::function<bool(char)> overload" << std::endl;
}
#endif
void myFunc(const std::string &seperator) {
std::cout << "std::string overload" << std::endl;
}
bool testCallback(char) {
return true;
}
int main()
{
myFunc("String literal");
myFunc(std::string("std::string"));
myFunc(testCallback);
}
Output:
std::string overload
std::string overload
std::function<bool(char)> overload
It looks like std::cout can't print member function's address, for example:
#include <iostream>
using std::cout;
using std::endl;
class TestClass
{
void MyFunc(void);
public:
void PrintMyFuncAddress(void);
};
void TestClass::MyFunc(void)
{
return;
}
void TestClass::PrintMyFuncAddress(void)
{
printf("%p\n", &TestClass::MyFunc);
cout << &TestClass::MyFunc << endl;
}
int main(void)
{
TestClass a;
a.PrintMyFuncAddress();
return EXIT_SUCCESS;
}
the result is something like this:
003111DB
1
How can I print MyFunc's address using std::cout?
I don't believe that there are any facilities provided by the language for doing this. There are overloads for operator << for streams to print out normal void* pointers, but member function pointers are not convertible to void*s. This is all implementation-specific, but typically member function pointers are implemented as a pair of values - a flag indicating whether or not the member function is virtual, and some extra data. If the function is a non-virtual function, that extra information is typically the actual member function's address. If the function is a virtual function, that extra information probably contains data about how to index into the virtual function table to find the function to call given the receiver object.
In general, I think this means that it's impossible to print out the addresses of member functions without invoking undefined behavior. You'd probably have to use some compiler-specific trick to achieve this effect.
Hope this helps!
I'd like to add to the other answers, that the reason that you are getting '1' printed instead of an address, is that, for some reason, the compiler is coercing your function pointer into a boolean, so that you are really calling ostream& operator<< (bool val);
This seems to be unrelated to the function being a member function.
You can uncover this kind of information with clang++ -cc1 -ast-dump:
(ImplicitCastExpr 0x3861dc0 <col:13, col:25> '_Bool' <MemberPointerToBoolean>
(UnaryOperator 0x3861940 <col:13, col:25> 'void (class TestClass::*)(void)' prefix '&'
(DeclRefExpr 0x38618d0 <col:14, col:25> 'void (void)' CXXMethod 0x3861500 'MyFunc' 'void (void)')))))
One way to do that is (I'm not sure it's portable) :
void TestClass::PrintMyFuncAddress(void)
{
void (TestClass::* ptrtofn)() = &TestClass::MyFunc;
cout << (void*&)ptrtofn<< endl;
}
working example : http://ideone.com/1SmjW
Pointers to member functions need memory, too. They also have a size. So how about printing out the memory of the pointer:
template<typename R, typename T, typename... Args>
std::string to_string(R (T::*func)(Args...))
{
union PtrUnion
{
R(T::*f)(Args...);
std::array<unsigned char, sizeof(func)> buf;
};
PtrUnion u;
u.f = func;
std::ostringstream os;
os << std::hex << std::setfill('0');
for (auto c : u.buf)
os << std::setw(2) << (unsigned)c;
return os.str();
}
You can use it this way:
class TestClass
{
void foo();
};
...
std::cout << to_string(&TestClass::foo) << std::endl;
I have created a type list. I then create a class using a template passing the type list. When I call the print function of the class with a some types not specified they are casted. How can I enforce the exact type at compile time? So if I use an unlisted type I get a compiler error.
Thanks.
template <class T, class U>
struct Typelist
{
typedef T Head;
typedef U Tail;
};
class NullType
{
};
typedef Typelist<int,Typelist<float,Typelist<char*,NullType> > > UsableTypes;
template<class T>
class MyClass
{
public:
void print(T::Head _Value) { std::cout << _Value; }
void print(T::Tail::Head _Value) { std::cout << _Value; }
void print(T::Tail::Tail::Head _Value) { std::cout << _Value; }
private:
};
MyClass<UsableTypes> testclass;
void TestMyClass()
{
int int_val = 100000;
float flt_val = 0.1f;
char* char_val = "Hi";
short short_val = 10;
std::string str_val = "Hello";
testclass.print( int_val ); // OK 8-)
std::cout << endl;
testclass.print( flt_val ); // OK 8-)
std::cout << endl;
testclass.print( char_val ); // OK 8-)
std::cout << endl;
testclass.print( short_val); // this compiles OK and works ??? 8-(
std::cout << endl;
testclass.print( str_val ); // compile error 8-)
std::cout << endl;
}
#Kerrek SB: Hi I thought it was going to help me with my next step, which was creating the print function depending on the t_list contents, Types and amounts of types. But I'm struggling to separate compile time processing and runtime processing. What I am trying to do is create a print function for each type in the list. So if the list has two types, two print functions will be created and if there are five types then five print functions will be created one for each type.
When I do this:
typedef Typelist<int,Typelist<float,Typelist<char*,NullType> > > UsableTypes;
MyClass<UsableTypes> newclass
Does this create three instance of MyClass one for each type in the list or does it create one instance and I have to create a print function for each type?
I feel I almost have all the blocks in my mind but just can’t fit them together. Any help you can offer would be gratefully received. Thanks.
Add a private function template
template<typename T> void print(T);
which doesn't need an implementation. This should catch all types for which no explicit print exists, and since it is private, it will give an error message.
You would have to make your print function into a template and then check whether the types match:
template <typename U>
void print(const U & u)
{
// use std::is_same<typename std::decay<T::Head>::type, typename std::decay<U>::type>::value
}
Here I'm stealing is_same and decay from <type_traits>, but if you don't have C++11, you can either take them from TR1 or from Boost, or just write them yourself, as they're very simple type modifier classes.
The conditional would best go into a static_assert, which is another C++11 feature, but there exist similar constructions for C++98/03 that produce a compile-time error under a certain condition.
You could take your arguments by non-const reference, forcing them to be the exact same type. However you can no longer use it with const variables or literals.