gpt4 book ai didi

c++ - 带模板参数的函数调用

转载 作者:行者123 更新时间:2023-12-03 10:04:21 25 4
gpt4 key购买 nike

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

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例如可以这样做。

最佳答案

您只能进行一次隐式用户转换,因此您可以调用 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)
  • 关于c++ - 带模板参数的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65235027/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com