无法将字符串文字分配给boxed std :: string向量

Phi*_*Lab 13 c++ constructor visual-c++ c++11 msvc12

这是我的类型系统的简化版本:

#include <string>
#include <vector>

template<typename T>
class Box {
public:
    Box(const T& value) : _value(value) {};
private:
    T _value;
    /* ... */
};

typedef Box<int> Int;
typedef Box<double> Double;
typedef Box<std::string> String;

int main(int argc, char* argv[]) {
    String a("abc");
    std::vector<String> b = { std::string("abc"), std::string("def") };

    // error C2664: 'Box<std::string>::Box(const Box<std::string> &)' : cannot convert argument 1 from 'const char' to 'const std::string &'
    std::vector<String> c = { "abc", "def" };
}
Run Code Online (Sandbox Code Playgroud)

虽然ab编译,c没有和原因似乎是我尝试初始化const char.这提出了两个问题:

  1. 为什么b可能但不是c?是因为嵌套模板std::vector<Box<std::string> >吗?

  2. 我可以c在不破坏一般拳击机制的情况下完成工作(参见typedef Box<double> Double

Jar*_*d42 18

c目前需要2个隐式用户转换(const char [N]- > std::string- > String),而只允许一个.

您可以添加模板构造函数 Box

template<typename T>
class Box {
public:
    Box() = default;
    Box(const Box&) = default;
    Box(Box&&) default;
    ~Box() = default;

    Box& operator=(const Box&) = default;
    Box& operator=(Box&&) = default;

    template <typename U0, typename ...Us,
              std::enable_if_t<std::is_constructible<T, U0, Us...>::value
                               && (!std::is_same<Box, std::decay_t<U0>>::value
                                  || sizeof...(Us) != 0)>* = nullptr>
    Box(U0&& u0, Us&&... us) : _value(std::forward<U0>(u0), std::forward<Us>(us)...) {}
private:
    T _value;
    /* ... */
};
Run Code Online (Sandbox Code Playgroud)

演示 DEMO2

  • 这件事需要限制.其中很多. (2认同)