相关疑难解决方法(0)

重载引用与const引用

我有以下代码:

#include <iostream>

template <typename T>
void f(T& x)        
{
    std::cout << "f(T& )" << std::endl; 
}

template <typename T>
void f(const T& x) 
{ 
    std::cout << "f(const T& )" << std::endl; 
}

int main() 
{
    int a = 0;
    const float b = 1.1;

    f(a); // call f(T&)
    f(b); // call f(const T&)
}
Run Code Online (Sandbox Code Playgroud)

输出是:

f(T& )
f(const T& )
Run Code Online (Sandbox Code Playgroud)

我的问题是:编译器如何知道要调用哪个函数?如果我从函数定义中删除引用,那么我会得到一个"模糊调用"类型的错误,即error: redefinition of 'f'.对我来说,它看起来f(T&)可以同样适用于两个调用,为什么const明确要求版本f(b)?

c++ pass-by-reference

9
推荐指数
2
解决办法
2108
查看次数

可能有尾随返回类型的条件重载?

假设您尝试执行以下操作:

template</* args */>
typename std::enable_if< /*conditional*/ , /*type*/ >::type
static auto hope( /*args*/) -> decltype( /*return expr*/ )
{
}
Run Code Online (Sandbox Code Playgroud)

是否可以将条件包含/重载(std::enable_if)与trailing-return-type(auto ... -> decltype())结合起来?

在使用预处理器的解决方案中,我不会感兴趣.我总是可以这样做

#define RET(t) --> decltype(t) { return t; }
Run Code Online (Sandbox Code Playgroud)

并扩展它以采取整个条件.相反,如果语言支持它而不使用返回类型的其他特征,即ReturnType<A,B>::type_t函数体中使用的任何特性,我感兴趣.

c++ templates sfinae c++11 trailing-return-type

1
推荐指数
1
解决办法
1505
查看次数