模板接受const但不接受文字 [英] Template accepts const but not literal

查看:72
本文介绍了模板接受const但不接受文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写模板时,class T可以用const类型代替.

When writing a template, class T may be substituted by a const type.

考虑:

template<class T> T& min(T& a, T& b) {
    return a < b ? a : b;
}

在以下情况下这将起作用:

This will work in the following cases:

int a = 1, b = 5;
const int c = 1, d = 5;
min(a, b); // T is int
min(c, d); // T is const int

但是使用文字(如此类)调用时将引发编译错误:

But will throw a compilation error when called with a literal (like so):

min(1, 5); // T is const int literal

类型为'int'的右值对类型为'int&'的非常量引用的无效初始化

invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

为什么? int文字不是const int吗?以及如何修改模板以允许使用文字呢?

Why? Isn't an int literal a const int? And how can the template be modified to allow working with literals?

(与gcc 6.3和MSVC 2015一致)

(consistent with gcc 6.3 and MSVC 2015)

推荐答案

int文字的类型为int,而不是const int.因此,推断出Tint,并且 int&无法绑定到prvalue .

int literals have type int, not const int. T is therefore deduced to be int, and int& can't bind to a prvalue.

编写这样一个函数的正确方法是完善参数,或者使用const T&,两者都可以绑定到任何东西.

The correct way to write such a function is to either perfect forward the arguments, or use const T&, both of which can bind to anything.

template<typename T, typename U>
auto min(T&& a, U&& b) -> decltype(a < b ? std::forward<T>(a) : std::forward<U>(b))
{
    return a < b ? std::forward<T>(a) : std::forward<U>(b); 
}

// Or...
template<typename T>
const T& min(const T& a, const T& b)
{
    return a < b ? a : b;
}

在完美传递参数的情况下,需要两个模板参数才能编译int a{}; min(a, 42);,因为它们的推导类型不同.

In the case of perfectly forwarding the arguments, the two template parameters are needed in order for int a{}; min(a, 42); to compile, as their deduced types are different.

这篇关于模板接受const但不接受文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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