开发者

Order of template arguments for a function

开发者 https://www.devze.com 2023-02-23 00:24 出处:网络
In below code among 2 template arguments, I use one of them implicit and another explicitly: class A {};

In below code among 2 template arguments, I use one of them implicit and another explicitly:

class A {};

template<typename ToType, typename FromType>
ToType CompileTimeCast (FromType pointer)
{
  return (ToType)(pointer);
}

int main ()
{
  A *pA;
  int *pi = CompileTimeCast<int*>(pA); // function invocation
}

It works fine. Now, if I swap ToType and FromType in argument list, compiler throws error as:

 error: no matching function for call to ‘CompileTimeCast(A*&)’

Was curious to know, why com开发者_如何学Pythonpiler complains when it knows that both arguments are different at function invocation and one argument is already used ?


When you explicitly specify template arguments, you have to specify them in order, just like you have to specify function arguments in the correct order, even if they are defaulted:

int *pi = CompileTimeCast<int*, const int*>(pA);

In this example, and assuming your original code, ToType is int* and FromType is const int*. If you explicitly specify only a subset of the template arguments, the compiler is forced to assume that your subset is the first few template arguments, in order. And all of the trailing template arguments must be deducible.

Note that for the set of template arguments that the compiler deduces, order doesn't matter. In your example, only FromType is deducible.

You have discovered the proper rationale for ordering template arguments: Order them by decreasing probability that your client want to explicitly specify them in the call of your function.


By swapping if you meant this:

template<typename FromType, typename ToType> //argument swapped their position!
ToType CompileTimeCast (FromType pointer)

Then the argument deduction wouldn't work anymore. Because when you write CompileTimeCast<int*>, then compiler would assume that int* is always the first argument in the function template argument list. And the second argument would be deduced by the compiler.

Now, you've to explicitly mention the types as:

int *pi = CompileTimeCast<A*, int*>(pA); //FromType=A*, ToType=int*


Compiler should be able to determine type of returned value using function call signature, not using any variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消