Need to solve a casting issue

Hey guys, I am completely new to C++ and have been trying to learn as I solve an assignment problem. The basis of it is that the program iterates through a tuple and prints the sum of all the numeric entries, along with the concatenation of all entries that can be cast to a string. I'm having an issue with the summing part because the specific element is being recognized as an int, but then when I try adding it to the running total it throws a "error: no match for ‘operator+=’ (operand types are ‘float’ and ‘std::__cxx11::basic_string<char>’)". I've tried casting from a string to an int, but this gives an error saying I cannot cast from int to int. Any help would be much appreciated!
Last edited on
The problem is that when, for example, the template is instantiated for a std::string, the line "total += a" still exists, and is an error. Maybe you should use template specialization instead.
That did the job thank you!
Last edited on
You're welcome. :-)
Some other points:
* You should include <typeinfo> to use typeid.
* You should probably compare typeid(a).name() or typeid(a).hash_code() instead of the std::type_info objects themselves.
* You use int32_t in your tuple definition but int in the typeid(). You should use the same type name in both places.
* You should pass the tuples as references instead of copies.
* You can remove tup from the version that just returns. This eliminates a possible compiler warning.
Last edited on
std::typeinfo is EqualityComparable, it can be used to check if two types referred to are the same.

There are no guarantees about the what std::type_info::name() yields;
"in particular, the returned string can be identical for several types and change between invocations of the same program."
https://en.cppreference.com/w/cpp/types/type_info/name
Maybe something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <tuple>

template <typename T> 
void f(T tuple)
{
  std::string acc_s{};
  double acc_x{};
  
  std::apply([&](auto&&... xs)
  { 
    ([&](auto&& x){
        if constexpr (std::is_convertible_v<decltype(x), std::string>) 
          acc_s += static_cast<std::string>(std::forward<decltype(x)>(x));
        if constexpr (std::is_convertible_v<decltype(x), double>)      
          acc_x += static_cast<double>(std::forward<decltype(x)>(x));  
     }(std::forward<decltype(xs)>(xs)), ...);
  }, std::move(tuple));
  
  std::cout << acc_s << '\n' << acc_x << '\n';
}

int main()
{
  f(std::tuple(0.1, 2, "Have", 100.f, " a ", 200.0, "nice", -15, " day"));
}
Last edited on
Topic archived. No new replies allowed.