Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.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++_Templates_Function_Return Value_Template Specialization - Fatal编程技术网

C++ C+中专门化函数模板的语法+;

C++ C+中专门化函数模板的语法+;,c++,templates,function,return-value,template-specialization,C++,Templates,Function,Return Value,Template Specialization,假设我有一个函数模板,其中type参数仅用作返回类型: template <typename T> T foo() { return whatever; } 模板 T foo() { 回报一切; } 那么,专门化该函数模板的正确语法是什么?以下两项似乎都有效: template <> std::string foo() { return whatever; } template <> std::string foo<std::str

假设我有一个函数模板,其中type参数仅用作返回类型:

template <typename T>
T foo()
{
    return whatever;
}
模板
T foo()
{
回报一切;
}
那么,专门化该函数模板的正确语法是什么?以下两项似乎都有效:

template <>
std::string foo()
{
    return whatever;
}

template <>
std::string foo<std::string>()
{
    return whatever;
}
模板
std::stringfoo()
{
回报一切;
}
模板
std::stringfoo()
{
回报一切;
}

这两者有什么区别吗?如果不是,惯用的方法是什么?

编译器将根据提供的信息(这里是函数返回类型)推断出正确的模板专门化


因此,这些语法具有完全相同的行为,一个比另一个更明确。

在大多数情况下,两者之间没有区别


如果您重载了多个模板函数,则可能需要使用第二种形式来消除关于要专门化哪个重载的歧义(如果您处于这种情况,则可能会遇到其他问题,例如,您还需要在调用位置显式)。

在本例中,在调用站点推断模板参数已经不可能了。