Click here to Skip to main content
15,392,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is code snippet i try to compile, which result to compile error:
convert const char * to int is invalid;

can anyone help debug this code ?
thanks in advance!

What I have tried:

#include <iostream>
#include <typeinfo>

using namespace std;
int sums() { return 0; }

template <typename Type, typename... T>
int sums(const Type s, const T... args)
    int res = 0;
    if (typeid(s) == typeid(int))
        res += s;
        cout << "not int" << s << endl;
    res += sums(args...);
    return res;

int main()
    cout << sums(1,"sir", 4) << endl;
    return 0;
Updated 28-Jun-22 23:21pm
0x01AA 29-Jun-22 5:49am
See here: Parameter pack(since C++11) -[^], section 'Pack expansion'
sirun wang 30-Jun-22 22:53pm
i use constexpr fix it. -> constexpr (std::is_integral<t>::value)

1 solution

The string "sir" is not a number: you can't add it to an integer directly, and there is no way to convert "sir" to a number at all!
sirun wang 29-Jun-22 5:28am
but i use typeid to skip this error, only when the type is int can execute res += s; when the string "sir" will not execute int + int.
sirun wang 29-Jun-22 6:43am
so the complier only check the type of parameter but not judge the if else suitation?
Greg Utas 29-Jun-22 7:39am
Yes, that's what the compiler will do when it instantiates the template. You can probably get around it by wrapping each argument in a class that effectively acts as a union.
sirun wang 29-Jun-22 7:48am
thank you, so pretty answer for me! have a nice day and enjoy your life.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900