相关疑难解决方法(0)

在 C++ 中函数 SFINAE 的方法

我在一个项目中大量使用 SFINAE 函数,但不确定以下两种方法(样式除外)之间是否存在任何差异:

#include <cstdlib>
#include <type_traits>
#include <iostream>

template <class T, class = std::enable_if_t<std::is_same_v<T, int>>>
void foo()
{
    std::cout << "method 1" << std::endl;
}

template <class T, std::enable_if_t<std::is_same_v<T, double>>* = 0>
void foo()
{
    std::cout << "method 2" << std::endl;
}

int main()
{
    foo<int>();
    foo<double>();

    std::cout << "Done...";
    std::getchar();

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

程序输出如预期:

method 1
method 2
Done...
Run Code Online (Sandbox Code Playgroud)

我已经看到方法 2 在 stackoverflow 中使用得更频繁,但我更喜欢方法 1。

这两种方法有什么不同吗?

c++ sfinae

45
推荐指数
2
解决办法
1889
查看次数

标签 统计

c++ ×1

sfinae ×1