C ++中的部分模板函数规范有效,但是为什么呢? [英] Partial template function specification in C++ works, but why?

查看:111
本文介绍了C ++中的部分模板函数规范有效,但是为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find out whether partial specification of templated functions is part of the C++ standard, or whether this is something compiler specific.

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

By partial specification, I mean specifying only the types the compiler can't deduce. So if I have a template function 'f' that takes 3 types, and one is used in a parameter and can be deduced, I might call 'f' with the form 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对此进行了测试.由于它似乎得到了编译器的广泛支持,因此我敢保证它是标准的一部分,但是有人可以确认吗?没有人有任何指向资源的链接或指针,这些链接或指针可能解释其为何起作用?

I've tested this with g++ 4.5.3, g++ 4.6.3, VS2010 and VS2012. Since it seems to be widely supported by the compilers, I'm betting it is part of the standard, but can anyone confirm that? Does anyone have any links or pointers to resources that might explain why this works?

推荐答案

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

Paragraph 14.8.1.2 of the C++03 standard states

可以从显式模板参数列表中省略可以推导的跟踪模板参数(14.8.2)."

"Trailing template arguments that can be deduced (14.8.2) may be omitted from the list of explicit template-arguments."

这篇关于C ++中的部分模板函数规范有效,但是为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆