template <typename StaticStringType>
StaticStringType MyToString()
{
std::string s;
return s;
}
int main()
{
MyToString();
// NO INSTANCE OF FUNCTION TEMPLATE MATCHES THE ARGUMENT LIST
}
我也尝试过:
template <typename StaticStringType>
auto MyToString() -> std::string
编译器无法推导模板参数,因为无法进行任何推导。
模板参数推导是在发送到函数的参数上完成的。没有参数,没有推导。
也许你要找的不是模板参数推导,但无论如何我都会先展示它。
这是此函数的示例,通过参数给出模板实参推导:
template <typename StaticStringType>
auto MyToString(StaticStringType value) -> StaticStringType
{
std::string s;
return value;
}
int main()
{
int value;
MyToString(value); // compiler deduces int, since `value` is of type int
}
如果您只是希望函数返回
std::string
,则不需要模板参数:
auto MyToString() -> std::string
{
std::string s;
return value;
}
或者让编译器推导返回类型:
auto MyToString() // return type deduced to be `-> std::string`
{
std::string s;
return value;
}