无法将字符串文字分配给装箱的std :: string矢量 [英] Can't assign string literal to boxed std::string vector

查看:90
本文介绍了无法将字符串文字分配给装箱的std :: string矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a simplified version of my type system:

#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" };
}

a b 编译, c 不能编译,原因似乎是我尝试从初始化const char 。这就提出了两个问题:

While a and b compile, c does not and the reason seems to be that I try to initialize from const char. This raises two questions:


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

我可以在不破坏常规的情况下使 c 工作吗拳击机制(参见 typedef Box< double> Double

Can I make c work without destroying the general boxing mechanism (cf. typedef Box<double> Double?


推荐答案

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

c currently need 2 implicit user conversions (const char [N] -> std::string -> String) whereas only one is allowed.

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

You may add template constructor to 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;
    /* ... */
};

演示
Demo2

这篇关于无法将字符串文字分配给装箱的std :: string矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆