lundi 22 janvier 2024

How to simplify these function template specializations?

I am working on some legacy code that has the following template defined in a header file:

template<typename T>
std::string convertToString(const T& t);

In the same header file, there are specializations for some user-defined types. In the .cpp file, there are specializations for the types int, unsigned short and unsigned long as follows:

template<>
std::string convertToString<unsigned short>(const unsigned short& s) {
    ... some implementation ...
}

template<>
std::string convertToString<int>(const int & s) {
    ... some implementation ...
}

template<>
std::string convertToString<unsigned long>(const unsigned long& value) {
    ... some implementation ...
}

The implementations don't make use of C++11's std::to_string function. I would like to simplify this code so that for all types that std::to_string supports, namely

int
long
long long
unsigned
unsigned long
unsigned long long
float
double
long double

the template specialization uses the simple implementation (e.g. for int):

template<>
std::string convertToString(const int& n) { return std::to_string(n); }

I could of course write down all template specializations for all the above mentioned types, but that doesn't seem like a nice way to do it. My current best solution to have these template specializations for all types that std::to_string takes is to add the following to my header file:

template<typename T>
std::string convertToString(const T& t);

template <typename T,
          typename = typename std::enable_if<std::is_arithmetic<T>::value>::type>
std::string convertToString(const T& t)
{
    return std::to_string(t);
}

I think this is close to a solution, but not yet as I get the following ambiguity error:

error: call of overloaded 'convertToString(long unsigned int&)' is ambiguous

referring me to the above two template functions as possible candidates. I don't quite understand why the first one is also a possible candidate if the second one exists...

How can I add template specializations for all the types that std::to_string supports, and also still allow for user-defined types T in the convertToString function template? Solution should be restricted to C++11 for now...

samedi 13 janvier 2024

C++: how to locate the exception?

I have the following test code.

#include <exception>
#include <iostream>

void terminate_handler() {
    auto const ep = std::current_exception();
    if(ep) {
        try {
            std::rethrow_exception(ep);
        } catch(const std::logic_error& le) {
            std::cerr << "terminating with std::logic_error: " << le.what()
                      << std::endl;
        }
    }
    std::abort();
}

int main(int argc, char* argv[]) {
    std::set_terminate(terminate_handler);
    std::string(0);
    return 0;
}

It is working fine, but I want to add filename and line number like below if possible.

terminating with std::logic_error: basic_string::_M_construct null not valid at main.cpp:26.

Segmentation fault on nullptr check when incrementing the ptr to iterate over an array

The following code, when compiled and run gives a segmentation fault. I was trying out the sample on page 12 of a Tour of C++ on a MacBook.

compilation command - clang++ -Wall -std=c++11 -o replacement.o replacement.cpp && ./replacement.o

Error message - 'zsh: segmentation fault ./replacement.o'

Full code -

#include <iostream>

int count_occurances(char* p, char x)
{
    int count = 0;
    // count number of times x occurs in p
    while (p != nullptr)
    {
        if (*p == x)
            ++count;
        ++p;
    }
    return count;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    char num_array[4] = {'a', 'b', 'b', 'c'};
    std::cout << "Running count occurances array" << count_occurances(num_array, 'b') << "done\n" ;
    return 0;
}

Essentially tried to iterate over the array by incrementing the pointer but somehow messing up the nullptr check, as a result it's accessing memory it shouldn't.