Search code examples
c++templatescompiler-errorsvariadic

error when trying compiling code with variadic parameters


When I try to compile the following code, I receive an C2672 and a C2783 error. I couldn't figure out how to fix it.

class Statement
{
public:
    template<typename T, typename ... Args>
    void Bind_All(Args... args)
    {
        std::vector<T> list = { args... };
    }
}

void func()
{
    Statement stmt;
    stmt.Bind_All(1, 2.5, "3");
}

error C2672: 'Statement::Bind_All': no matching overloaded function found

error C2783: 'void Statement::Bind_All(Args...)': could not deduce template argument for 'T'

Thanks!


Solution

  • Here is an example of how this variadic template could be completed and used:

    class Statement {
    public:
        template <typename T>
        static void Bind_All(T value) {}
        template<typename T,typename ... Args>
        static void Bind_All(T value, Args... args)
        {
            Bind_All(args...);
        }
    };
    
    void func()
    {
        Statement stmt;
        stmt.Bind_All(1,2.5,"3");
    }
    
    int main()
    {
        func();
        return 0;
    }
    

    or, if you want to see that different types were actually used:

    #include <iostream>
    #include <typeinfo>
    
    class Statement {
    public:
        template <typename T>
        static void Bind_All(T value) 
        {
            std::cout << typeid(value).name() << ":";
            std::cout << value << '\n';
        }
    
        template<typename T,typename ... Args>
        static void Bind_All(T value, Args... args)
        {
            std::cout << typeid(value).name() << ":";
            std::cout << value << '\n';
    
            Bind_All(args...);
        }
    };
    
    void func()
    {
        Statement stmt;
        stmt.Bind_All(1,2.5,"3");
    }
    
    int main()
    {
        func();
        return 0;
    }
    

    On my system this yields:

    int:1
    double:2.5
    char const * __ptr64:3