简体   繁体   中英

Deducing std::string from const char* or char* when creating a std::tuple

I'm wondering if there is an easy way to deducing a std::string from a const char* when making a tuple. That would be possible with my own tuple implementation but I'm wondering if it is possible with std::tuple

For example in the code below storage_ will have the type of :

std::tuple<int, int, const char*>

std::tuple<const char*, char*>

I would like to get :

std::tuple<int, int, std::string>

std::tuple<std::string, std::string>

#include <tuple>
#include <string>
#include <string.h>
template<typename T>
class foo
{
public:
    foo(T storage) : storage_(std::move(storage)) {}
private:
    T storage_;
};

int main()
{
    char* s2 = strdup("123");

    foo f { std::make_tuple(12,123,"1234") };

    foo f2 { std::make_tuple("321", s2) };

    free(s2);
    // still want to keep s2 stored in f2
}

I know I can write std::tuple<int,std::string> t1 = std::make_tuple(123,"12"); but that doesn't solve my problem as I want to have any number of arguments passed in any order

Solution: https://wandbox.org/permlink/MsUxZ18SYD1K2ujv

Regardless of wether this is something you should be doing or not, the question can still be answered as asked:

I don't think you'll be able to pull this off without providing your own make_tuple .

Thankfully, a lot of the heavy lifting can still be done by std::make_tuple() . All you have to do, really, is explicitely specify the template arguments, instead of letting them be deduced:

template<typename T>
struct Promoted {
    using type = T;
};

template<>
struct Promoted<const char *> {
    using type = std::string;
};

template<typename T>
using Promoted_t = typename Promoted<T>::type;

template<typename... ArgsT>
auto make_my_tuple(ArgsT&&... args) {
    return std::make_tuple<Promoted_t<std::decay_t<ArgsT>>...>(std::forward<ArgsT>(args)...);
}

Disclaimer: The code I posted is not meant to be a complete solution. It's a guideline on how I would tackle the issue. There are probably some edge cases not being covered here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM