Pointer Decay with Higher Precedence Than Template Function? - g++

I have the following code:
#include <iostream>
template <typename T>
void foo(const T& v) { //version 1
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void foo(char* v) {//version 2
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void foo(const char* v) {//version 3
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main() {
char s1[] = "1234";
const char* s2 = "2345";
foo(s1);
foo(s2);
}
The output is:
void foo(char*)
void foo(const char*)
I thought s1 needs to go through pointer decay and so the template function foo() is a better match.
If I remove the 2nd foo()'s declaration and definition, then compiler chooses not to go through pointer decay and chooses the template function foo().
Now, I am confused what the rule is for compiler to choose which function to bind to/call.
Thanks!

That behavior is governed by overload resolution rules, which are quite complicated. A good write-up can be found here: https://en.cppreference.com/w/cpp/language/overload_resolution
For your particular case, a non-template function foo(char* ) with implicit conversion wins over template function.

Related

Defining strict_real_policies for reals with a comma decimal character

I would like to create a custom policy derived from strict_real_policies that will parse reals, such as "3,14", i.e. with a comma decimal point as used e.g. in Germany.
That should be easy, right?
#include <iostream>
#include <string>
#include <boost/spirit/home/x3.hpp>
template <typename T>
struct decimal_comma_strict_real_policies:boost::spirit::x3::strict_real_policies<T>
{
template <typename Iterator>
static bool
parse_dot(Iterator& first, Iterator const& last)
{
if (first == last || *first != ',')
return false;
++first;
return true;
}
};
void parse(const std::string& input)
{
namespace x3=boost::spirit::x3;
std::cout << "Parsing '" << input << "'" << std::endl;
std::string::const_iterator iter=std::begin(input),end=std::end(input);
const auto parser = x3::real_parser<double, decimal_comma_strict_real_policies<double>>{};
double parsed_num;
bool result=x3::parse(iter,end,parser,parsed_num);
if(result && iter==end)
{
std::cout << "Parsed: " << parsed_num << std::endl;
}
else
{
std::cout << "Something failed." << std::endl;
}
}
int main()
{
parse("3,14");
parse("3.14");
}

Tagging (or coloring) CGAL objects

I am trying to use CGAL to perform some simple 2D CSG operations. Here is an example of an intersection of two polygons.
The actual problem is tracking down the origin (marked with color) of each segment in resulting polygon.
I would like to know if that is possible, maybe with some hacking on the CGAL itself. Any suggestion will be highly appreciated.
Unfortunately, there is no out-of-the-box way doing it. However, it doesn't require too much (famous last words...). You need to do two things described below. The first is supported by the API. The second is not, so you will need to patch a source file. A simple example is provided further bellow. Notice that the data you need, that is, the specification of the origin of each edge, ends up in a 2D arrangement data structure. If you want to obtain the polygons with this data, you need to extract them from the arrangement. You can obtain the header pgn_print.h, used in the example, from the 2D-Arrangement book.
Use an instance of CGAL::Polygon_set_2<Kernel, Container, Dcel>, where the Dcel is substituted with an extended Dcel, the halfedge of which is extended with a label that indicates the origin of the halfedge (i.e., first polygon, second polygon, or both in case of an overlap).
Patch the header file Boolean_set_operations_2/Gps_base_functor.h. In particular, add to the body of the three functions called create_edge() statements that set the label of the resulting halfedges according to their origin:
void create_edge(Halfedge_const_handle h1, Halfedge_const_handle h2,
Halfedge_handle h)
{
h->set_label(3);
h->twin()->set_label(3);
}
void create_edge(Halfedge_const_handle h1, Face_const_handle f2,
Halfedge_handle h)
{
h->set_label(1);
h->twin()->set_label(1);
}
void create_edge(Face_const_handle f1, Halfedge_const_handle h2,
Halfedge_handle h)
{
h->set_label(2);
h->twin()->set_label(2);
}
#include <list>
#include <vector>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Boolean_set_operations_2.h>
#include <CGAL/Polygon_set_2.h>
#include "pgn_print.h"
/*! Extend the arrangement halfedge */
template <typename X_monotone_curve_2>
class Arr_labeled_halfedge :
public CGAL::Arr_halfedge_base<X_monotone_curve_2>
{
private:
unsigned m_label;
public:
Arr_labeled_halfedge() : m_label(0) {}
unsigned label() const { return m_label; }
void set_label(unsigned label) { m_label = label; }
virtual void assign(const Arr_labeled_halfedge& he)
{
CGAL::Arr_halfedge_base<X_monotone_curve_2>::assign(he);
m_label = he.m_label;
}
};
template <typename Traits>
class Arr_labeled_dcel :
public CGAL::Arr_dcel_base<CGAL::Arr_vertex_base<typename Traits::Point_2>,
Arr_labeled_halfedge<typename Traits::
X_monotone_curve_2>,
CGAL::Gps_face_base>
{
public:
Arr_labeled_dcel() {}
};
typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
typedef Kernel::Point_2 Point_2;
typedef CGAL::Polygon_2<Kernel> Polygon_2;
typedef CGAL::Polygon_with_holes_2<Kernel> Polygon_with_holes_2;
typedef std::vector<Point_2> Container;
typedef CGAL::Gps_segment_traits_2<Kernel, Container> Traits_2;
typedef Arr_labeled_dcel<Traits_2> Dcel;
typedef CGAL::Polygon_set_2<Kernel, Container, Dcel> Polygon_set_2;
typedef std::list<Polygon_with_holes_2> Pwh_list_2;
typedef Polygon_set_2::Arrangement_2 Arrangement_2;
typedef Arrangement_2::Edge_const_iterator Edge_const_iterator;
void print_result(const Polygon_set_2& S)
{
std::cout << "The result contains " << S.number_of_polygons_with_holes()
<< " components:" << std::endl;
Pwh_list_2 res;
S.polygons_with_holes(std::back_inserter(res));
for (Pwh_list_2::const_iterator hit = res.begin(); hit != res.end(); ++hit) {
std::cout << "--> ";
print_polygon_with_holes(*hit);
}
const Arrangement_2& arr = S.arrangement();
for (Edge_const_iterator it = arr.edges_begin(); it != arr.edges_end(); ++it) {
std::cout << it->curve()
<< ", " << it->label()
<< std::endl;
}
}
int main()
{
// Construct the two input polygons.
Polygon_2 P;
P.push_back(Point_2(0, 0));
P.push_back(Point_2(5, 0));
P.push_back(Point_2(3.5, 1.5));
P.push_back(Point_2(2.5, 0.5));
P.push_back(Point_2(1.5, 1.5));
std::cout << "P = "; print_polygon(P);
Polygon_2 Q;
Q.push_back(Point_2(0, 2));
Q.push_back(Point_2(1.5, 0.5));
Q.push_back(Point_2(2.5, 1.5));
Q.push_back(Point_2(3.5, 0.5));
Q.push_back(Point_2(5, 2));
std::cout << "Q = "; print_polygon(Q);
// Compute the union of P and Q.
Polygon_set_2 intersection_set;
intersection_set.insert(P);
intersection_set.intersection(Q);
print_result(intersection_set);
// Compute the intersection of P and Q.
Polygon_set_2 union_set;
union_set.insert(P);
union_set.join(Q);
print_result(union_set);
return 0;
}

Why do I need to refer an object of an inherited class through a pointer to its base class?

Why do I need to refer an object of an inherited class through a pointer to its base class, when I am aware that the call to a function, exclusive to the inherited class, will produce a compilation time error?
Why Polymorphism?
Edit:
Here's a small piece of code as an example:
enum Suit { Spade, Heart, Club, Diamond };
enum Val { Ace=1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
class Card {
private:
Val val;
Suit suit;
public:
Card(Val val, Suit suit) : val(val), suit(suit) {
cout << "Card constructor called" << endl;
}
int get_val() { return val; }
Suit get_suit() { return suit; }
};
class BlackJackCard : public Card {
public:
int garbage;
BlackJackCard(Val val, Suit suit) : Card(val, suit), garbage(9) {}
int get_val() {
Val tmpVal = (Val)Card::get_val();
if(tmpVal == 1) return 11;
if(tmpVal < 10) return tmpVal;
return 10;
}
int exclusive_to_BJC() {
cout << "I do nothing!! and the garbage value my object holds is " << garbage << endl;
}
};
int main() {
Card *newCard = new BlackJackCard(King,Spade);
cout << newCard->get_val() << endl; // 13
cout << newCard->get_suit() << endl; // 0
/*Why should I use a base class referencing if I can't access all the*/
/*members of the object I have constructed(except for the virtual functions).*/
// cout << newCard->exclusive_to_BJC() << endl;
// cout << newCard->garbage << endl;
BlackJackCard *new_bjCard = new BlackJackCard(King,Spade);
cout << new_bjCard->get_val() << endl; // 10
cout << new_bjCard->get_suit() << endl; // 0
cout << new_bjCard->exclusive_to_BJC() << endl;
}
Mainly for that reason (follow the link): low coupling.
If you talk about pointers, I understand C++, so you can take look at this explained example too.
You don't need to, you can. In fact, the vast majority of the time, it is better to take advantage of this possibility, to obtain better code. Consider:
class Vehicle
{
};
class Car : public Vehicle
{
};
int f(Vehicle *)
{
// code written here will be able to work on any type of vehicle.
}
OOP allows you to write f() in way that all vehicles are treated the same way, from the point of view of f(). In fact, a Car can have specialized functionality for Vehicle's function, without f() even needing to know.

After I disable g++ return value optimization,Why the last call of constructor for temporary reference?

I compile the c++ code using the follow command to disable return value.
g++ -fno-elide-constructors rvoptimazation.cpp -o test
But the output of ./test is
10
10
10
13
0xbfdf0020
13
I am confused by the last call of the constructor. Can anyone explain which line of the code will call the constructor after return in operator*? Thanks in advance.
#include<iostream>
using namespace std;
class Rational{
public:
Rational(int x ,int y){
_a = x;
_b = y;
cout << __LINE__ << endl;
}
Rational(Rational const &t){
cout << __LINE__ << endl;
}
Rational operator*(Rational const &t){
Rational re = Rational(_a * t._a ,_b * t._b);
cout << &re << endl;
return re;
//return *this;
}
Rational get()
{
return *this;
}
public:
int _a ,_b;
};
int main()
{
Rational r1(1 ,2);
Rational r2(2 ,3);
r1 * r2;
// cout << &r3 << endl;
}
operator* returns by value, so the returned object must be constructed. The statement return re calls the copy constructor to do that.
I think the explanation at Return value optimization is quite clear.

can't get address of the dll function with GetProcAddress

I created a dll with VS C++ (of course as a dll project) with the following code of the header file:
#pragma once
#include <iostream>
#include "..\..\profiles/ProfileInterface.h"
using namespace std;
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface
{
public:
CExportCoordinator(void);
virtual ~CExportCoordinator(void);
CProfileInterface* Create();
void Initialize();
void Start();
};
Here is .cpp file of the dll:
#include "StdAfx.h"
#include "ExportCoordinator.h"
CExportCoordinator::CExportCoordinator(void)
{
}
CExportCoordinator::~CExportCoordinator(void)
{
}
CProfileInterface* CExportCoordinator::Create(){
cout << "ExportCoordinator3 created..." << endl;
return new CExportCoordinator();
}
void CExportCoordinator::Initialize(){
cout << "ExportCoordinator3 initialized..." << endl;
}
void CExportCoordinator::Start(){
cout << "ExportCoordinator3 started..." << endl;
}
I exported the whole class CExportCoordinator because I need to use all three methods it offers. Following is the code from the main application loading the, above given, dll on the fly.
typedef CProfileInterface* (WINAPI*Create)();
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hLib = LoadLibrary(name);
if(hLib==NULL) {
cout << "Unable to load library!" << endl;
return NULL;
}
char mod[MAXMODULE];
GetModuleFileName(hLib, (LPTSTR)mod, MAXMODULE);
cout << "Library loaded: " << mod << endl;
Create procAdd = (Create) GetProcAddress(hLib,"Create");
if (!procAdd){
cout << "function pointer not loaded";
}
return;
}
On the output I get that correct library is loaded, but that function pointer procAdd is NULL. I thought it had something to do with name mangling and added extern "C" when exporting the class in header of dll, but nothing changed. Btw, I used dll export viewer for viewing the exported functions of the class, and the whole class is exported correctly.
Any help?
UPDATE
there is an error in the header file of dll. I shouldn't be using extern "C" __declspec(dllexport) before class because then class won't be exported at all. If I use class __declspec(dllexport) CExportCoordinator then the class is exported correctly, but anyway I can't get the address of the function other than NULL.
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface
{
This is nonsense. A class cannot be "extern C"
... inside the class ...
CProfileInterface* Create();
This creates a member function of the class, which is not probably what you want. For one thing, it will be mangled in the DLL, second, it will not be callable without the this pointer. Probably, you need this declaration:
extern "C" __declspec(dllexport) CProfileInterface* Create();
and implemntation:
extern "C" __declspec(dllexport) CProfileInterface* Create(){
cout << "ExportCoordinator3 created..." << endl;
return new CExportCoordinator();
}
It seems to me that you should declare Create method as a static method and export this method only. If you will stay have NULL in GetProcAddress you should examine exports of your DLL with respect of Dependency Walker (see http://www.dependencywalker.com/) and modify the name of the function "Create" to something like "_Create" or "_Create#2".