首页 > 解决方案 > 模板接受 const 但不接受字面量

问题描述

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

考虑:

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

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

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

但是当使用文字调用时会抛出编译错误(像这样):

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

从“int”类型的右值初始化“int&”类型的非常量引用无效</p>

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

(与 gcc 6.3 和 MSVC 2015 一致)

标签: c++templatesgeneric-programming

解决方案


int文字有类型int,没有const intT因此推断为int,并且int&不能绑定到 prvalue

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

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);编译,因为它们推导的类型不同。


推荐阅读