开发者

How does boost::lexical_cast take only one template type?

I've looked through the mess that is lexical_cast.hpp and this continues to escape me.

How is lexical_cast, whose 'base definition' takes both a template source and destination, able to accept grammar such as lexical_cast<int>("7")? I don't see how it can o开发者_开发问答nly need a templated return type and not need you to give the type of the parameter without doing something illegal like partial template specialization.

Note: I understand how you could do this with a single template type and overloads for different parameters, but I fail to understand how lexical_cast's is based off of a template function requiring both source and destination template types.


Template arguments can be deduced from the function arguments:

template <typename T>
void foo(const T& x)
{
    // T is the type of X
}

foo(5); // T is be int
foo("hello"); //T is const char[6]


template <class Ret, class Input>
Ret lexical_cast(Input i)
{
   // ...
}

The Input type is deduced based on the argument that's passed in.


It's because the compiler can deduce the type of arguments from the arguments, however only if it's possible and not ambiguous. The compiler will not deduce the return type. That's why the return type is required but the types of arguments are not.


Basically, there are three sources for function template parameters:

  1. Explicitly provided template arguments.
  2. Default values
  3. Deduced from function arguments

A function template can be instantiated if all template parameters can be resolved. It's not required that each template argument is resolved from the same source. E.g. in the case of boost::lexical_cast<OutType, InType>, the InType is typically deduced from the function argument and OutType is explicitly provided.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜