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

标签 c++ templates template-argument-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 对此进行了测试。由于它似乎得到了编译器的广泛支持,我敢打赌它是标准的一部分,但有人能证实吗?有没有人有任何资源链接或指针可以解释为什么会这样?

最佳答案

C++03 标准状态的第 14.8.1.2 段

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

关于c++ - C++ 中的部分模板函数规范有效,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554496/

相关文章:

c++ - 当第一行完成时井字游戏不会结束

c++ - Visual Studio C++ : Debug Assertion Failed

c++ - 使用函数指针进行类型删除不适用于 GCC

c++ - 编译器抛出 "ambiguous overload for operator"

c++ - 如何复制txt文件中的字符串?

c++ - 检测用户离屏幕的距离

c++ - 为什么它是使用 GCC 的模糊函数调用?模板推导失败?

c++ - 完美转发类模板参数推导

c++ - 如何使用模板专门化模板?

C++ 关于函数模板