The following test program reproduces compilation errors within the context of a larger program:
#include <algorithm>
#include <iostream>
#include <vector>
using std::for_each;
using std::vector;
using std::cout;
using std::endl;
template<typename T, typename C = vector<T>>
class display_container{
public:
display_container(const C& cr):this->cr(cr){this->();}
~display_container(){}
private:
constexpr void operator () (void){if(cr.empty()){cout << "NULL" << " ";} else{for_each(cr.begin(), cr.end(), [](const T& crt){cout << crt << " ";});}}
const C& cr;
};
int main (void){
int n = 5;
vector<int> vec(n, 0);
display_container d(vec);
cout << endl;
return 0;
}
The following is a log of the compiler errors:
g++ -ggdb -std=c++17 -Wall -Werror=pedantic -Wextra -c code.cpp
code.cpp: In constructor ‘display_container<T, C>::display_container(const C&)’:
code.cpp:12:40: error: expected identifier before ‘this’
display_container(const C& cr):this->cr(cr){this->();}
^~~~
code.cpp:12:40: error: expected ‘{’ before ‘this’
code.cpp: In function ‘int main()’:
code.cpp:23:28: error: class template argument deduction failed:
display_container d(vec);
^
code.cpp:23:28: error: no matching function for call to ‘display_container(std::vector<int>&)’
code.cpp:12:9: note: candidate: template<class T, class C> display_container(const C&)-> display_container<T, C>
display_container(const C& cr):this->cr(cr){this->();}
^~~~~~~~~~~~~~~~~
code.cpp:12:9: note: template argument deduction/substitution failed:
code.cpp:23:28: note: couldn't deduce template parameter ‘T’
display_container d(vec);
^
code.cpp:10:7: note: candidate: template<class T, class C> display_container(display_container<T, C>)-> display_container<T, C>
class display_container{
^~~~~~~~~~~~~~~~~
code.cpp:10:7: note: template argument deduction/substitution failed:
code.cpp:23:28: note: ‘std::vector<int>’ is not derived from ‘display_container<T, C>’
display_container d(vec);
^
make: *** [makefile:20: code.o] Error 1
I presume that the remaining errors trickle down from the first error related to the inline constructor definition for the display_container template class.
Any suggestions on what is wrong with the code related to inline constructor definition?
TIA
The compiler can not fetch the template type of vector yet:
#include <algorithm>
#include <iostream>
#include <vector>
using std::for_each;
using std::vector;
using std::cout;
using std::endl;
template<typename T, typename C = vector<T>>
class display_container{
public:
display_container(const C& cr): cr(cr) { (*this)(); }
~display_container(){}
private:
constexpr void operator () (void){if(cr.empty()){cout << "NULL" << " ";} else{for_each(cr.begin(), cr.end(), [](const T& crt){cout << crt << " ";});}}
const C& cr;
};
int main (void){
int n = 5;
vector<int> vec(n, 0);
display_container<int> d(vec);
cout << endl;
return 0;
}
You couldn't (and don't need) qualify data members in member initializer list by this, they're expected to be the identifier. The correct syntax should be
display_container(const C& cr):cr(cr){(*this)();}
You should dereference on this and then call operator() on it (as showed abolve), or you can call operator() explicitly like this->operator()(); (which looks ugly).
You should specify the template argument for display_container.
display_container<int> d(vec);
LIVE
Related
Can anyone help me with this errors. When i compile this simple program
#include<queue>
using namespace std;
template<typename Queue>
int qtest(Queue & queue,typename Queue::Type item)
{
return 0;
}
int main()
{
std::queue<int> q;
int t = qtest(q,3);
}
I get the errors like below
In function 'int main()':
error: no matching function for call to 'qtest(std::queue<int>&, int)'
note: candidate is:
note: template<class Queue> int qtest(Queue&, typename Queue::Type)
note: template argument deduction/substitution failed:
In substitution of 'template<class Queue> int qtest(Queue&, typename Queue::Type) [with
Queue = std::queue<int>]':
required from here
error: no type named 'Type' in 'class std::queue<int>'
warning: unused variable 't' [-Wunused-variable]
std::queue doesn't have a member type called Type. That's what the compiler is telling us. I'm guessing what you're looking for is std::queue<int>::value_type.
template<typename Queue>
int qtest(Queue & queue,typename Queue::value_type item)
{
return 0;
}
Reference: cppreference
I'm trying to map string to function pointer, so that I can call the function with iter->second(arg) instead of if-else.
I have written a simple one without class, and it works as expected.
But when I modify it as below, it shows compile errors.
#include <functional>
#include <iostream>
#include <unordered_map>
#include <string>
using std::string;
class A{
private:
int a(int num, string s) { return s.size() + num; }
int b(int num, string s) { return num - s.size(); }
public:
void ido(string str){
typedef std::function<int(int, string)> process_func;
std::unordered_map<string, process_func> m;
m.insert(std::make_pair<string, process_func>("a", &A::a));
// using std::placeholders::_1;
// m.insert(std::make_pair<string, process_func>("a", std::bind(&A::a, this, _1)));
// m["a"] = std::bind(&A::a, this, _1);
// m.insert({{"a", &A::a}, {"b", &A::b}});
auto x = m.find(str);
if(x == m.end()) {
std::cout << "Not supported!" << std::endl;
}
std::cout << x->second(10, "hello") << std::endl;
}
};
int main(int argc, char* argv[]) {
A a;
a.ido(string(argv[1]));
return 0;
}
The errors are:
function.cc: In member function ‘void A::ido(std::string)’:
function.cc:17:65: error: no matching function for call to ‘make_pair(const char [2], int (A::*)(int, std::string))’
m.insert(std::make_pair<string, process_func>("a", &A::a));
^
function.cc:17:65: note: candidate is:
In file included from /usr/include/c++/4.8.2/utility:70:0,
from /usr/include/c++/4.8.2/tuple:38,
from /usr/include/c++/4.8.2/functional:55,
from function.cc:1:
/usr/include/c++/4.8.2/bits/stl_pair.h:276:5: note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
make_pair(_T1&& __x, _T2&& __y)
^
/usr/include/c++/4.8.2/bits/stl_pair.h:276:5: note: template argument deduction/substitution failed:
function.cc:17:65: note: cannot convert ‘&A::a’ (type ‘int (A::*)(int, std::string) {aka int (A::*)(int, std::basic_string<char>)}’) to type ‘std::function<int(int, std::basic_string<char>)>&&’
m.insert(std::make_pair<string, process_func>("a", &A::a));
What does the error mean? How to fix it?
While your functions 'a' and 'b' do not depend on 'this' (they do not access anything inside class A), the compiler is not smart enough to deduce this. So the error means that you are trying to convert 'pointer to method' to 'pointer to function', which is incorrect conversion. 'Pointer to method' requires and object to be called on. You need to declare methods 'a' and 'b' as 'static' to indicate that they are actually standalone functions, not methods of the class.
#include <bits/stdc++.h>
using namespace std;
template<class T = string>
void f(T &&s) {
cout << s << endl;
}
int main() {
string s("1234");
f(s);
f("1234");
return 0;
}
Can be compiled.
#include <bits/stdc++.h>
using namespace std;
void f(string &&s) {
cout << s << endl;
}
int main() {
string s("1234");
f(s);
f("1234");
return 0;
}
I replace T to string, the code can not be compiled.
error:
❯ g++-8 -std=c++11 a.cpp && ./a.out
a.cpp: In function 'int main()':
a.cpp:10:11: error: cannot bind rvalue reference of type 'std::__cxx11::string&&' {aka 'std::__cxx11::basic_string<char>&&'} to lvalue of type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'}
f(s);
^
a.cpp:4:10: note: initializing argument 1 of 'void f(std::__cxx11::string&&)'
void f(string &&s) {
^
I'm so confused.
There are some exceptions to template type inference.
If a function template receives an rvalue reference and we passed in an lvalue reference,compiler will inference it as a lvalue reference.That is the reason that std::move works correctly.
template <typename T>
typename remove_reference<T>::type&& move(T&& t)
{
return static_cast<typename remove_reference<T>::type&&>(t);
}
Boost's <boost/any.hpp> has:
template<typename ValueType>
ValueType any_cast(any & operand);
template<typename ValueType>
inline ValueType any_cast(const any & operand);
(among other variants.) Shouldn't this combination cause ambiguity in calls such as boost::any_cast<int>(my_any); ?
I'm asking because if I write this program:
#include <boost/any.hpp>
#include <iostream>
template<typename ValueType>
ValueType any_cast(boost::any & operand)
{
return boost::any_cast<ValueType>(operand);
}
int main()
{
int x = 123;
boost::any my_any(x);
std::cout << "my_any = " << any_cast<int>(my_any) << "\n";
return 0;
}
I do get a complaint about ambiguity:
g++ -std=c++14 -O3 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:14:57: error: call of overloaded 'any_cast(boost::any&)' is ambiguous
std::cout << "my_any = " << any_cast<int>(my_any) << "\n";
^
main.cpp:5:11: note: candidate: ValueType any_cast(boost::any&) [with ValueType = int]
ValueType any_cast(boost::any & operand)
^~~~~~~~
In file included from main.cpp:1:0:
/usr/local/include/boost/any.hpp:281:22: note: candidate: ValueType boost::any_cast(const boost::any&) [with ValueType = int]
inline ValueType any_cast(const any & operand)
^~~~~~~~
/usr/local/include/boost/any.hpp:258:15: note: candidate: ValueType boost::any_cast(boost::any&) [with ValueType = int]
ValueType any_cast(any & operand)
^~~~~~~~
Why would the calls be ambiguous? The way you call the function the any argument is an lvalue. Thus, the any argument will either be const-qualified in which case the second overload is the only potential match or it is not const-qualified in which case the first overload is the better match (there is no conversion needed while the second overload would need a conversion from any& to any const&). If you call the function with a temporary any, it could bind to an rvalue overload (i.e., taking any&&) or, if that doesn't exist, it can bind to the const-qualified overload but not the non-const-qualified overload, again, not causing any ambiguity.
Actually, there is something interesting happening here: without the overload in the global namespace the function using the explicit template argument cannot be used! However, as soon as any function template is present, even a non-matching one, it can be used! Here is an example:
namespace foo {
struct bar {};
template <typename T> void bar_cast(bar&) {}
template <typename T> void bar_cast(bar const&) {}
template <typename T> void bar_cast(bar&&) {}
}
struct whatever;
template <typename T> void bar_cast(whatever);
int main()
{
foo::bar b;
bar_cast<int>(b);
}
I took the code from
http://www.boost.org/doc/libs/1_54_0/libs/graph/doc/edge_list.html
included my header,
#include <iostream> // for std::cout
#include <utility> // for std::pair
#include <algorithm> // for std::for_each
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/edge_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/bellman_ford_shortest_paths.hpp>
#include <boost/graph/johnson_all_pairs_shortest.hpp>
#include <fstream>
#include <ctime>
using namespace boost;
int main(){
enum { u, v, x, y, z, N };
char name[] = { 'u', 'v', 'x', 'y', 'z' };
typedef std::pair<int,int> E;
E edges[] = { E(u,y), E(u,x), E(u,v),
E(v,u),
E(x,y), E(x,v),
E(y,v), E(y,z),
E(z,u), E(z,x) };
int weight[] = { -4, 8, 5,
-2,
9, -3,
7, 2,
6, 7 };
typedef boost::edge_list<E*> Graph;
Graph g(edges, edges + sizeof(edges) / sizeof(E));
std::vector<int> distance(N, std::numeric_limits<short>::max());
std::vector<int> parent(N,-1);
distance[z] = 0;
parent[z] = z;
bool r = boost::bellman_ford_shortest_paths(g, int(N), weight,
distance.begin(),
parent.begin());
if (r)
for (int i = 0; i < N; ++i)
std::cout << name[i] << ": " << distance[i]
<< " " << name[parent[i]] << std::endl;
else
std::cout << "negative cycle" << std::endl;
return 0;
}
compile with
g++ -O3 boostexampl.cpp -I/user/include/
I got this error
make -k
g++ -O3 boostexampl.cpp -I/user/include/
boostexampl.cpp: In function ‘int main()’:
boostexampl.cpp:40:61: error: no matching function for call to ‘bellman_ford_shortest_paths(Graph&, int, int [10], std::vector<int>::iterator, std::vector<int>::iterator)’
boostexampl.cpp:40:61: note: candidates are:
In file included from boostexampl.cpp:7:0:
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:91:8: note: template<class EdgeListGraph, class Size, class WeightMap, class PredecessorMap, class DistanceMap, class BinaryFunction, class BinaryPredicate, class BellmanFordVisitor> bool boost::bellman_ford_shortest_paths(EdgeListGraph&, Size, WeightMap, PredecessorMap, DistanceMap, BinaryFunction, BinaryPredicate, BellmanFordVisitor)
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:91:8: note: template argument deduction/substitution failed:
boostexampl.cpp:40:61: note: candidate expects 8 arguments, 5 provided
In file included from boostexampl.cpp:7:0:
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:210:8: note: template<class EdgeListGraph, class Size, class P, class T, class R> bool boost::bellman_ford_shortest_paths(EdgeListGraph&, Size, const boost::bgl_named_params<P, T, R>&)
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:210:8: note: template argument deduction/substitution failed:
boostexampl.cpp:40:61: note: mismatched types ‘const boost::bgl_named_params<P, T, R>’ and ‘int [10]’
In file included from boostexampl.cpp:7:0:
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:222:8: note: template<class EdgeListGraph, class Size> bool boost::bellman_ford_shortest_paths(EdgeListGraph&, Size)
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:222:8: note: template argument deduction/substitution failed:
boostexampl.cpp:40:61: note: candidate expects 2 arguments, 5 provided
In file included from boostexampl.cpp:7:0:
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:229:8: note: template<class VertexAndEdgeListGraph, class P, class T, class R> bool boost::bellman_ford_shortest_paths(VertexAndEdgeListGraph&, const boost::bgl_named_params<T, Tag, Base>&)
/usr/local/include/boost/graph/bellman_ford_shortest_paths.hpp:229:8: note: template argument deduction/substitution failed:
boostexampl.cpp:40:61: note: mismatched types ‘const boost::bgl_named_params<T, Tag, Base>’ and ‘int’
make: *** [examp] Error 1
make: Target `main' not remade because of errors.
Compilation exited abnormally with code 2 at Sat Oct 5 14:24:35
I am kind of stuck here. Any help would be appreciated. Sorry I provides the full code, but I don't know where is problem is. Is boost examples guaranteed to work? did they change the interface but didn't change on-line example? Or I didn't include headers.