C ++中的部分模板函数规范有效,但为什么呢?

时间:2012-11-25 19:16:41

标签: c++ templates template-deduction function-templates

我试图找出模板化函数的部分规范是否是C ++标准的一部分,或者这是否是编译器特定的。

通过部分规范,我的意思是仅指定编译器无法推断的类型。因此,如果我有一个模板函数'f'需要3种类型,并且一个在参数中使用并且可以推导出来,我可以用f<type, type>(parameter)

形式调用'f'

以下是一个例子:

#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对此进行了测试。由于它似乎得到了编译器的广泛支持,我认为它是标准的一部分,但任何人都可以证实这一点吗?有没有人有任何链接或指向可能解释其原因的资源?

1 个答案:

答案 0 :(得分:14)

C ++ 03标准的第14.8.1.2段陈述

“可以推导出的尾随模板参数(14.8.2)可以从显式模板参数列表中省略。”