问题
I am using self-written template methods to load and save settings from/into Qt's QSettings
. QSettings
receive/return data of type QVariant
and QVariant
has constructors taking basic types like int
and double
, but not 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.
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:
#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;
}
回答1:
Create an overloaded non-template for std::string
that forwards to your method.
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);
}
来源:https://stackoverflow.com/questions/60817890/how-to-realize-automatic-type-conversion-for-template-methods