显式转换和模板转换运算符 [英] Explicit conversion and templated conversion operator

查看:97
本文介绍了显式转换和模板转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以某种方式扩展Microsoft类型_variant_t,以便它接受与其他类型之间的隐式/显式转换.为此,我编写了以下课程:

I wanted to somehow extend the Microsoft type _variant_t so it accepts implicit/explicit conversions to/from additional types. To do so, I wrote the following class:

class value_type
{
  public:
    /* Constructors */
    value_type(const std::string& str) : m_variant(str.c_str()) {}
    template <typename Type> value_type(const Type& value) : m_variant(value) {}

    /* Conversion operators */
    operator const _variant_t&() const { return m_variant; }
    operator std::string() const { return static_cast<const char*>(m_variant); }
    template <typename Type> operator Type() const { return static_cast<Type>(m_variant); }
  private:
    _variant_t m_variant;
};

也就是说,如果代码中的每个_variant_t实例都替换为value_type,则它有效" 相同.

That is, if every instance of _variant_t in the code is replaced with value_type, it "works" the same.

让我们考虑以下函数,该函数返回_variant_t:

Lets consider the following function, which returns a _variant_t:

_variant_t foo();

如果我写:

std::string bar()
{
  value_type v = foo();
  return v;
}

它编译得很好.

但是,如果我像这样更改以前的代码:

But if I change the previous code like that:

std::string bar()
{
  return value_type(foo());
}

或:

std::string bar()
{
  return static_cast<std::string>(value_type(foo()));
}

编译失败,并显示以下消息:

The compilation fails with the following message:

configuration.cpp(41):错误C2668:'std :: basic_string< _Elem,_Traits,_Ax> :: basic_string':对重载函数的歧义调用

configuration.cpp(41) : error C2668: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string' : ambiguous call to overloaded function

如果我删除template <typename Type> operator Type...行,则所有内容都会编译.

If I remove the template <typename Type> operator Type... line, everything compiles.

现在,我理解了编译器的内容(它不知道要使用哪个运算符),但是我不明白为什么:在转换为std::string时使用operator std::string似乎是合乎逻辑的.我想念什么?

Now I understand what the compilater says (it doesn't know which operator to use) but I don't understand why: It would seem logical to use the operator std::string when converting to std::string. What am I missing ?

谢谢.

推荐答案

问题是字符串的构造函数已重载.因此,如果返回涉及调用字符串构造函数,则有多种选择:参数可以转换为const char*allocator<char>string.

The problem is that string's constructor is overloaded. So if returning involves invoking a string constructor, then there are multiple choices: argument could be converted to const char*, allocator<char> or string.

static_cast<string>(x)string(x)相同.

我想您的第一个错误示例应为return string(foo());,而不是return value_type(foo());

I suppose your first faulty example should read return string(foo());, not return value_type(foo());

这篇关于显式转换和模板转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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