小编Rya*_*yan的帖子

为什么std :: is_same为这两种类型提供了不同的结果?

在下面的代码中,为什么有两种调用方式fun:fun(num)fun<const int>(num)编译时给出不同的结果?

#include <iostream>
using namespace std;

template<typename T, typename = typename enable_if<!std::is_same<int, T>::value>::type>
void fun(T val)
{
    cout << val << endl;
}

int main(void)
{
    const int num = 42;
    fun(num);  //ERROR!

    fun<const int>(num);  //Right

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates const template-function argument-deduction

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

编译器如何决定调用哪个函数模板?

编译器在重载两个函数模板时如何决定调用哪个函数:

#include <iostream>
#include <typeinfo>

#ifndef B1
template <typename T1, typename T2> 
auto max(T1 a, T2 b) {
    std::cout << "auto version called" << std::endl;
    return b < a ? a : b;
}
#endif

#ifndef B2
template <typename RT, typename T1, typename T2> 
RT max(T1 a, T2 b) {
    std::cout << "RT version called" << std::endl;
    return b < a ? a : b;
}
#endif

template <typename T>
void print(T t) {
    std::cout << typeid(t).name() << std::endl;
} …
Run Code Online (Sandbox Code Playgroud)

c++ templates

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