简体   繁体   中英

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'

You have to provide the template parameter explicitly:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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