Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类型推断不适用于C++;_C++ - Fatal编程技术网

C++ 模板类型推断不适用于C++;

C++ 模板类型推断不适用于C++;,c++,C++,我有两个模板 整数的第一个 template <class T> T myMin(T a, T b) { return (a < b) ? a : b; } 但是对于第二个模板,我必须使用类型 int c = myMin(1,2); std::string st = convert<std::wstring, std::string>(sw); std::string st=convert(sw); 没有以下条件,我无法使用它: std::stri

我有两个模板

整数的第一个

template <class T>
T myMin(T a, T b)
{
    return (a < b) ? a : b;
}
但是对于第二个模板,我必须使用类型

int c = myMin(1,2);
std::string  st = convert<std::wstring, std::string>(sw);
std::string st=convert(sw);
没有以下条件,我无法使用它:

std::string  st = convert(sw);  // this fails with the error "no accordance found for convet<TypeFrom, TypeTo>(wstring)"
std::string st=convert(sw);//此操作失败,错误为“未找到Convert(wstring)的一致性”

知道为什么吗?

模板参数不能从函数的返回类型推导出来。您可以交换模板参数的顺序,以便能够对输入参数进行类型推断:

好吧,同样的限制也适用于重载函数(出于同样的原因)。在
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 *
std::string st=convert(sw);//复制构造函数
std::string st=convert(sw);//const char的构造函数*

其主要思想是,虽然它对您来说可能并不含糊(而我将转换为
const char*
而不是直接转换为
std::string
),但对编译器来说,它是含糊不清的,并且不是编译器的角色来做出这种选择。

我明白了!谢谢。这意味着我应该跳过=运算符,并将返回类型/值用作其他参数。比亚恩·斯特劳斯特鲁普没有考虑函数演绎的返回类型,有什么好的理由吗?@NECIP你应该问问他;)更严重的是,注意到,不能通过它的返回类型(浮点f*)/代码>和 int f*()/c> > C++来重载函数。这种限制可能是因为调用
f()
在许多情况下都是不明确的(
f();
单独,
g(f())
g
作为
float
int
的重载,等等…。@NECIP请查看我的更新答案,以获得更多可读的信息,了解为什么(IMO)您不能这样做。
// 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));
int f ();
float f ();
std::string st = convert <std::string> (sw) ; // Copy constructor
std::string st = convert <const char *> (sw) ; // Constructor from const char *