watertavi
watertavi

Reputation: 81

Why can't C++ compiler infer template parameters?

Consider the following example:

template<typename TI>
char trunc(TI IN){
        return (char)IN;
}

template <typename TO, typename TI>
TO applyf(TO (OP)(TI), TI IN){
        return OP(IN);
}

template <typename TO, typename TI,
          TO (OP)(TI)>
TO applyt(TI IN){
        return OP(IN);
}

int main(){
        int i = -21;
        char r1 = applyf(trunc<int>, i);
        char r2 = applyt<char, int, trunc>(i);
        char r3 = applyt<trunc>(i);
}

When I compile this code in g++ (with C++11), I get the errors:

Function.cpp:21:12: error: no matching function for call to 'applyt'

   char r3 = applyt<trunc>(i);

Function.cpp:13:4: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'TO' TO applyt(TI IN){

So my question is simple: The input argument type is obvious - an int - and to me TO should be obvious.

Why can't TO and TI be inferred, but they can be inferred in r1?

Upvotes: 3

Views: 141

Answers (1)

user1084944
user1084944

Reputation:

trunc is a function template, not a type, and so it cannot match typename TO.

Upvotes: 4

Related Questions