简体   繁体   English

具有返回类型参数的函数模板特化

[英]function template specialization with return type argument

Is it possible to specialize a template with an argument for the return value. 是否可以使用返回值的参数来专门化模板。 I am getting an error trying to do the template specialization shown below. 尝试执行以下所示的模板专门化操作时出现错误。 So I am currently declaring the two specializations as different functions using macros to 'avoid' duplicating code. 因此,我目前正在将这两个专业声明为使用宏来避免重复代码的不同功能。

#include <iostream>

template<class T1,class T2>
inline T1 func(const T2& a) { return T1(3.5);}

template<>
inline float func(const int& a) { return (1.0); }

template<>
inline double func(const float& a) {return (2.0); }

int main() {
  func(2);  
  return 0;
}

The error is: 错误是:

    temp.cpp:13:3: error: no matching function for call to 'func'
  func(2);      
  ^~~~
temp.cpp:4:11: note: candidate template ignored: couldn't infer template argument 'T1'
inline T1 func(const T2& a) { return T1(3.5);}
          ^
1 error generated.

Specializing a return type isn't really different than any other specialization. 专门化返回类型与其他专门化并没有什么不同。 The problem isn't with how this works, but how it is called. 问题不在于它如何工作,而是如何调用。

template<class T1,class T2>
inline T1 func(const T2& a)
{
    return T1(3.5);
}

func(2); //with T2 = int, what is T1?

The compiler has no way to know what the return type should be. 编译器无法知道返回类型应该是什么。 A specialization is specific instructions on what to do if the template parameters match, so it still needs both template parameters first. 专业化是关于模板参数匹配时的操作的特定说明,因此它仍然首先需要两个模板参数。 If you specify the first template parameter, it will work. 如果指定第一个模板参数,它将起作用。

func<float>(2); //returns 1.0

As noted in the comments, though, overloading is preferable to specialization. 但是,如评论中所述,重载比专业化更可取。

float func(const int&);
double func(const float&);

This way, it doesn't get stuck on guessing a return type. 这样,就不会陷入猜测返回类型的麻烦。

The error message tells you quite clear what is the problem: 错误消息告诉您很清楚问题所在:

temp.cpp:4:11: note: candidate template ignored: couldn't infer template argument 'T1' temp.cpp:4:11:注意:候选模板被忽略:无法推断模板参数“ T1”

You have to provide the template parameter explicitly: 您必须显式提供template参数:

int main() {
  func<float,int>(2);  
  return 0;
}

The reason is that the compiler cannot deduce the return type that you want to use. 原因是编译器无法推断您要使用的返回类型。 T2 can be determined from the parameter you are passing, but for T1 any type would make a match, thus the compiler cannot decide. T2可以从您传递的参数中确定,但是对于T1任何类型都可以匹配,因此编译器无法确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM