Search code examples
c++c++17initializer-list

std::initializer_list with std::thread


myNameSpace::functionName(this, {"abc", "abc1"});  // working fine

working fine, but

std::thread(myNameSpace::functionName<ClassName>(this, {"abc", "abc1"})); 
                     //error: invalid use of void expression.

Please suggest me what I am missing here. or how to do it.

namespace myNameSpace {
    template<typename T>
    void functionName(T* cm, std::initializer_list<std::string_view> args) { ... }
}

Solution

  • First, that is not how you start a thread. You are calling it, and passing the result as an argument to start the thread. But, void is not a valid argument for starting a thread, nor is it indeed any sort of useful expression in any sense.

    You'd be writing something like this instead:

    std::thread(&myNameSpace::functionName<ClassName>, this, {"abc", "abc1"});
    

    Your next problem is that there is no facility in the language for the compiler to deduce what you mean by {"abc", "abc1"} there. With a direct function call to functionName, it can work it out, because the function call machinery knows what the candidate overloads are, but that is just not the case with this "broken down" construction.

    It's possible to fix that by specifying the type:

    std::thread(&myNameSpace::functionName<ClassName>, this, std::initializer_list<std::string_view>{"abc", "abc1"});
    

    However, I recommend you just pass (and accept) a std::vector<std::string_view> instead. It'll be much easier and much simpler.