模板类型推导在C++中不起作用
Template type deduction not working in C++
我有两个模板。
整数的第一个
template <class T>
T myMin(T a, T b)
{
return (a < b) ? a : b;
}
字符串的第二个
template <class TypeFrom, class TypeTo>
TypeTo convert(TypeFrom &from)
{
return static_cast<TypeTo>(from);
}
template <>
std::string convert<std::wstring, std::string>(std::wstring &from)
{
return std::string(from.begin(), from.end());
}
我可以使用的第一个模板不使用类型
int c = myMin(1,2);
但对于第二个模板,我必须使用类型
std::string st = convert<std::wstring, std::string>(sw);
我不能使用它没有:
std::string st = convert(sw); // this fails with the error "no accordance found for convet<TypeFrom, TypeTo>(wstring)"
知道为什么吗?
template <class TypeTo, class TypeFrom >
TypeTo convert(TypeFrom &from)
{
return static_cast<TypeTo>(from);
}
template <>
std::string convert<std::string, std::wstring>(std::wstring &from)
{
return std::string(from.begin(), from.end());
}
// Partial deduction
std::string st = convert<std::string>(sw);
基本上,你不能做convert(sw)
,因为它在很多情况下可能是模糊的,例如:
// Call without using the return value
convert(sw);
// Call with return value sent to an overloaded function
void g (std::string) ;
void g (int) ;
g(convert(sw));
AFAIK,同样的限制适用于重载函数(出于同样的原因)。在C++
(以及Java等许多语言)中,不能有以下内容:
int f ();
float f ();
事实上,如果你仔细想想,即使你的调用也是模棱两可的,因为std::string
有多个构造函数,所以我应该这样做:
std::string st = convert <std::string> (sw) ; // Copy constructor
std::string st = convert <const char *> (sw) ; // Constructor from const char *
其主要思想是,虽然它对您来说可能不模糊(而我会转换为const char *
而不是直接转换为std::string
吗?),但对编译器来说是模糊的,编译器角色不能做出这种选择。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用