带模板参数的函数调用

短剑

我编写了一个简单的类模板:

template <class T>
class my_class
{
public:
    my_class(T value)
        : my_Value(value)
    {
    }
private:
    T my_Value;
};

现在,我可以在简单的函数签名中使用此模板,例如: my_function(my_class<std::string> my_string)

当我想调用该函数时,我可以轻松地使用它:

auto my_instance = my_class<std::string>("my value");
my_function(my_instance);

但是我想实现的是这样的函数调用:

my_function("my value")

我的班级模板应该为我隐式转换为模板的类型。我想我需要某种运算符重载。

std:optional 可以做到这一点。

贾罗德42

您只能有一个隐式用户转换,因此您的呼叫const char*无效。

有几种选择,

  • 为my_class添加另一个构造函数

    my_class(T value) : my_Value(value) {}
    
    template <typename U, std::enable_if_t<std::is_convertible<U, T>, int> = 0>
    my_class(U value) : my_Value(value) {}
    
  • 为my_function添加重载,

    void my_function(my_class<std::string> my_string)
    void my_function(const char* s) { return my_function(my_class<std::string>{s}); }
    
  • 更改呼叫站点以使用std::string以下命令进行呼叫

    my_function(std::string("my value"))
    
    using namespace std::string_literals;
    my_function("my value"s)
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章