函数重载及SFINAE

1. C语言不支持函数重载

main.c

c 复制代码
// gcc main.c
void f(int x, int y){}

void f(double x, double y){}

int main(){}

使用指令gcc main.c编译是会报错的,因为C语言是不支持函数重载的,报错信息如下:

bash 复制代码
main.c:4:6: error: conflicting types for 'f'; have 'void(double,  double)'
    4 | void f(double x, double y){}
      |      ^
main.c:2:6: note: previous definition of 'f' with type 'void(int,  int)'
    2 | void f(int x, int y){}
      |      ^

换成g++ main.c即可编译成功(或者将main.c改成main.cpp使用gcc main.cpp也可编译成功,即让编译器把代码当作C++处理即可)。

2. 关于函数重载编译器会做的事

a. 将所有对应的"同名"候选函数,做成一个集合。

b.根据函数声明,从集合中移除一些不合适的候选函数。此步骤主要依靠SFINAE。

c.在集合中剩余的函数中,依据参数,挑选一个最合适的函数。如果挑选不到,或者无法决定哪个最合适,会报错。

d.如果步骤c中挑选到了最合适的函数,还会继续做一些检查,比如是否是delete的。

3. SFINAE

3.1 SFINAE简单示例

cpp 复制代码
#include <iostream>
#include <typeinfo>
#include <type_traits>

/* 此函数仅会被占用字节数大于4的类型匹配上 */
template<class T>
typename std::enable_if<(sizeof(T)>4)>::type len() {
    std::cout << "sizeof(" << typeid(T).name() << ") is " << sizeof(T) << std::endl;
}

/* 此函数仅会被占用字节数小于等于4的类型匹配上 */
template<class T>
typename std::enable_if<(sizeof(T) <= 4)>::type len() {
    std::cout << "sizeof(" << typeid(T).name() << ") is " << sizeof(T) << std::endl;
}

auto main()->int {
    len<double>();  // sizeof(double) is 8
    len<float>();   // sizeof(float) is 4
    len<char>();    // sizeof(char) is 1
}

3.2 不使用SFINAE时编译器未匹配到合适的重载函数

cpp 复制代码
#include <iostream>
#include <vector>
#include <array>
#include <typeinfo>

template<class T, size_t N>
size_t foo(const T(&)[N]) {
    std::cout << "array's size: " << N << std::endl;
    return N;
}

template<class T>
typename T::size_type foo(const T& container) {
    std::cout << "container's size: " << container.size() << std::endl;   // 错误 C2039	"size": 不是 "Bar" 的成员
    return container.size();                                              // 错误 C2039	"size": 不是 "Bar" 的成员
}

size_t foo(...) {
    std::cout << "variadic" << std::endl;
    return 0;
}

class Bar {
public:
    using size_type = size_t;
};

auto main()->int {
    int a[] = {1,2,3,4,5};
    std::vector<short> vec{ 5,6,7,8,9,0 };
    foo(a);
    foo(vec);
    foo(4);

    //std::cout << typeid(Bar::size_type).name() << std::endl;
    foo(Bar());  // !!!报错是因为此句!!!
}

对上述代码进行编译的时候会报错,报错信息如注释。

本想让foo(Bar());匹配到size_t foo(...),但实际匹配到是template<class T> typename T::size_type foo(const T& container),而Bar却没有size()方法。

3.3 使用SFINAE时让编译器匹配到合适的重载函数

SFINAE"Substitution Failure Is Not An Error"替换失败不是个错误。

cpp 复制代码
#include <iostream>
#include <vector>
#include <array>
#include <typeinfo>

template<class T, size_t N>
size_t foo(const T(&)[N]) {
    std::cout << "array's size: " << N << std::endl;
    return N;
}

/* 通过T().size()的方式使得所有没有size()方法的类无法匹配该函数,从而达到SFINAE的目的 */
template<class T>
decltype(T().size(), typename T::size_type()) foo(const T& container) {
    std::cout << "container's size: " << container.size() << std::endl;
    return container.size();
}

size_t foo(...) {
    std::cout << "variadic" << std::endl;
    return 0;
}

class Bar {
public:
    using size_type = size_t;
};

auto main()->int {
    int a[] = {1,2,3,4,5};
    std::vector<short> vec{ 5,6,7,8,9,0 };
    foo(a);      // array's size: 5
    foo(vec);    // container's size: 6
    foo(4);      // variadic

    std::cout << typeid(Bar::size_type).name() << std::endl;  // m
    foo(Bar());  // variadic

    decltype(int()) ab;
    std::cout << double() << ", " << int() << std::endl;  // 0, 0
}

3.4 利用std::enable_if实现SFINAE让编译器匹配到合适的重载函数

cpp 复制代码
class Bar {
public:
    using size_type = size_t;
};

template<class T, size_t N>
size_t foo(const T(&)[N]) {
    std::cout << "array's size: " << N << std::endl;
    return N;
}

template<class T, class U = typename std::enable_if<!std::is_same_v<T, Bar>>::type>
typename T::size_type foo(const T& container) {
    std::cout << "container's size: " << container.size() << std::endl;
    return container.size();
}

size_t foo(...) {
    std::cout << "variadic" << std::endl;
    return 0;
}

auto main()->int {
    int a[] = {1,2,3,4,5};
    std::vector<short> vec{ 5,6,7,8,9,0 };
    foo(a);
    foo(vec);
    foo(4);

    //std::cout << typeid(Bar::size_type).name() << std::endl;
    foo(Bar());
}

输出:

bash 复制代码
array's size: 5
container's size: 6
variadic
variadic

4. std::enable_ifstd::is_same用法拓展

4.1 示例一

cpp 复制代码
#include <iostream>
#include <type_traits>

class CFoo1{
public:
    using size_type = unsigned int;
};

class CFoo2{
public:
    using size_type = unsigned int;
};

template<class T, typename std::enable_if<std::is_same<T, CFoo1>::value>::type* = nullptr>
void bar(){
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

template<class T, typename std::enable_if<std::is_same<T, CFoo2>::value>::type* = nullptr>
void bar(){
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

auto main()->int {
    bar<CFoo1>();
    bar<CFoo2>();
}

输出:

bash 复制代码
void bar() [with T = CFoo1; typename std::enable_if<std::is_same<T, CFoo1>::value>::type* <anonymous> = 0]
void bar() [with T = CFoo2; typename std::enable_if<std::is_same<T, CFoo2>::value>::type* <anonymous> = 0]

4.2 示例二

与示例一的不同之处在于非类型的模板参数是否有默认值,示例一有默认值在调用时第二个参数可以不给,示例二无默认值调用时需要显示实例化。

cpp 复制代码
#include <iostream>
#include <type_traits>

class CFoo1{
public:
    using size_type = unsigned int;
};

class CFoo2{
public:
    using size_type = unsigned int;
};

template<class T, typename std::enable_if<std::is_same<T, CFoo1>::value>::type* /*= nullptr*/>
void bar(){
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

template<class T, typename std::enable_if<std::is_same<T, CFoo2>::value>::type* /*= nullptr*/>
void bar(){
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

auto main()->int {
    bar<CFoo1, nullptr>();
    bar<CFoo2, nullptr>();
}

输出:

bash 复制代码
void bar() [with T = CFoo1; typename std::enable_if<std::is_same<T, CFoo1>::value>::type* <anonymous> = 0]
void bar() [with T = CFoo2; typename std::enable_if<std::is_same<T, CFoo2>::value>::type* <anonymous> = 0]

4.3 示例三

cpp 复制代码
#include <iostream>
#include <typeinfo>
#include <type_traits>

template<class T>
typename std::enable_if<(sizeof(T)>4)>::type len() {
   std::cout << "sizeof(" << typeid(T).name() << ") is " << sizeof(T) << std::endl;
}

template<class T>
typename std::enable_if<(sizeof(T) <= 4)>::type len() {
   std::cout << "sizeof(" << typeid(T).name() << ") is " << sizeof(T) << std::endl;
}

auto main()->int {
   len<double>();  // sizeof(double) is 8
   len<float>();   // sizeof(float) is 4
   len<char>();    // sizeof(char) is 1
}
相关推荐
-西门吹雪5 分钟前
现代C++ 并发编程-学习指南
java·jvm·c++
aaPIXa6222 小时前
C++ TensorRT Edge-LLM 边缘推理框架:从原理到实战
开发语言·c++·edge
nianniannnn3 小时前
c++复习自存--标准模板库STL
开发语言·c++·windows
努力努力再努力wz4 小时前
【高性能网络库与HTTP Server系列】:基于主从 Reactor 模型实现高性能 C++ 网络库与 HTTP Server
开发语言·网络·数据结构·数据库·c++·网络协议·http
Robot_Nav4 小时前
C++ 面试常问问题汇总:基础语法、面向对象、STL、多线程与设计模式
c++·设计模式·面试
一拳一个呆瓜4 小时前
【STL】iostream 编程:使用插入运算符并控制格式
c++·stl
盐焗鹌鹑蛋4 小时前
【C++】二叉搜索树
c++
哎呦,帅小伙哦4 小时前
C++工程实战: 预处理宏、宏重定义避坑、LOG_TAG业务实践与__COUNTER__深度解析
c++
IVVi0jToe5 小时前
高效C++线程池设计与实现
java·c++·安全
^yi5 小时前
【C++】内存管理
开发语言·c++