简体   繁体   中英

initializer list and conversion to everything, construction order

Situation like:

#include <utility>
#include <typeinfo>
#include <iostream>

struct C1
{
    char const* str; 
    template <typename T> operator T() const { std::cout << "Convert to " << typeid(T).name() << "\n"; return {}; }
};

struct C2
{
    C2(C1 const&) { std::cout << "C2(C1)\n"; }
    C2(std::initializer_list<std::pair<char const*, int>>) { std::cout << "C2(list)\n"; }
};

int main()
{
    C1 c1{};
    C2 c2{c1};
}

Output indicates that C2(list) is being called.

I would like C2(C1) to be called for C1 argument, but I need the parameters of std::initializer list to remain deducible and convertible, and I can not replace it with variadic-templated version. I just want to control the construction order, but here //2 is not even template. Suppose type std::pair can be deserialized in normal conditions. C++14 may be used

You may use the explicit keyword to prevent a constructor from implicit type conversions:

    explicit C2(std::initializer_list<std::pair<char const*, int>>) {} // 2

See: What does the explicit keyword mean in C++?

The following selects C2(C1) style for both style, {...} and ({...}) (in strict C++11 Standards, for the ({...}) style, it will select the second, because C1 is an aggregate and special rules applied for it. This is no longer the case for more recent Standards.). This works by making the second constructor no longer be an initializer constructor.

template<typename T>
struct id { typedef T type; };

struct C1 {
    char const* str; 
    template <typename T> operator T() const 
    { std::cout << "Convert to " << typeid(T).name() << "\n"; return {}; }
};

struct C2 {
    C2(C1);
    template<typename T = std::initializer_list<std::pair<char const*, int>>>
    C2(typename id<T>::type);
};

int main() {
    C1 c1{};
    C2 c2{c1};
    C2 c21({c1});
}

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