jeudi 28 novembre 2019

How to constraint the parameter package type in c++11? And How to implement the template in cpp?

For the first quesion:

I want to write a function to concatenation the strings, and it can receive multiple strings;

#include <string>
#include <vector>
#include <type_traits>

template <class... Args, typename std::enable_if<std::is_same<typename std::decay<Args...>::type, std::string>::type>::type>
std::string foo(const std::string &first, const Args &... senconds) {
    std::string delimiter = "$$";
    std::string ret = first;
    std::vector<std::string> vec{senconds...};
    for (auto second = vec.rbegin(); second != vec.rend(); second++) {
        ret = delimiter + *second + delimiter + ret;
    }
    return ret;
}

but when I invoke it like:

std::string name = "x";
name = foo(name, "xxx");

the compiler will throw an error:

error: no matching function for call to ‘foo(std::__cxx11::string&, const char [4])’

and there will be some note:

note: couldn't deduce template parameter ‘<anonymous>’

I think I should modify the constraint in the template, and I've tried all the related methods in the type_traits, but none of them works.

For the second question:

I want to hide the implementation of some function, but for the template function, it's unable to put the definition in the .hpp, and put the implementation in the .cpp, the compiler will throw a undefined reference error. Is there any elegant way to solve this?

Thanks.

Aucun commentaire:

Enregistrer un commentaire