简体   繁体   English

如何实现模板方法的自动类型转换?

[英]How to realize automatic type conversion for template methods?

I am using self-written template methods to load and save settings from/into Qt's QSettings .我正在使用自己编写的模板方法从/到 Qt 的QSettings加载和保存设置。 QSettings receive/return data of type QVariant and QVariant has constructors taking basic types like int and double , but not std::string . QSettings接收/返回QVariant类型的数据, QVariant具有采用intdouble等基本类型的构造函数,但不是std::string

My template method can therefore easily be used for int and double , but when using std::string I get compile error messages that there is no matching function call, because there is no known conversion from std::__cxx11::basic_string<char> to the types accepted by QVariant 's constructors.因此,我的模板方法可以轻松用于intdouble ,但是在使用std::string我收到编译错误消息,指出没有匹配的函数调用,因为没有来自std::__cxx11::basic_string<char>已知转换到QVariant的构造函数接受的类型。

Of course I can solve the problem by writing a specialization of my template method.当然,我可以通过编写我的模板方法的特化来解决这个问题。 Still, I am hesitating to do that, because there is exactly one little call that causes the problem.尽管如此,我还是犹豫要不要这样做,因为只有一个小电话会导致问题。 The rest of the code is just fine for all types.其余代码适用于所有类型。

Is it possible to provide a user-defined type conversion such that the compiler can automatically use for type-conversion when compiling the template method?是否可以提供用户定义的类型转换,以便编译器在编译模板方法时可以自动使用类型转换?

Here is a minimal example that tries to reproduce the situation without Qt classes:这是一个最小的例子,它试图在没有 Qt 类的情况下重现这种情况:

#include <string>
#include <vector>

class A
{
public:

    A(int)
    {
    }

    A(double)
    {
    }
};

std::vector<A> globalStorage;

template <typename Type>
void store(Type element)
{
    // A lot of lengthy storage preparation code
    // ...
    //

    // Final Storage
    globalStorage.push_back(A(element));
}

// TODO: A specialization of the template method solves the problem. Is there
// another way to provide a user-defined type conversion?
template <>
void store<std::string>(std::string element)
{
    // A lot of lengthy storage preparation code
    // ...
    //

    globalStorage.push_back(A(std::stoi(element)));
}

int main()
{
    double number1 = 1.0;
    int number2 = 2.0;
    float number3 = 3.0;

    store (number1);
    store (number2);
    store (number3);

    std::string number4 = "4";
    store(number4);

    return 0;
}

Create an overloaded non-template for std::string that forwards to your method.为转发到您的方法的std::string创建一个重载的非模板。

template <typename Type>
void store(Type element)
{
    // A lot of lengthy storage preparation code
    // ...
    //

    // Final Storage
    globalStorage.push_back(A(element));
}

void store(const std::string& s) {
    //convert s to QString or char* or a number, as you want
    auto converted_element = ...;
    store(converted_element);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM