我正在尝试确定模板函数的部分指定是否是C++标准的一部分,还是这仅仅属于编译器特定的功能。
所谓部分指定,指的是仅指定编译器无法推导出来的类型。例如,如果我有一个接受3种类型的模板函数"f",并且其中一个用在参数中可以被推导出来,那么我可以使用以下形式调用"f": f<type, type>(parameter)
以下是一个示例:
#include <iostream>
#include <tuple>
#include <string>
template<class A, class B, class C>
std::tuple<A, B> test(C c)
{
// do something based on c, return tuple with types A and B
return std::make_tuple(A(), B());
}
int main(void)
{
// I expected I would have to use this form. Specify all parameters.
std::tuple<int, int> value3 = test<int, int, int>(5);
// Here, I only specified the return value types, did not specify the parameter type, yet it compiles.
auto value1 = test<int, int>("c-string");
// Similar example here. Return types specified, parameter type deduced. Compiles fine.
auto value2 = test<std::string, int>(42);
return 0;
}
我已经使用g++ 4.5.3,g++ 4.6.3,VS2010和VS2012进行了测试。由于这似乎得到了编译器的广泛支持,我打赌这是标准的一部分,但有人可以确认吗?是否有任何链接或指向可能解释为什么这样做的资源?