在C ++中使用SFINAE的方法

问题描述 投票:22回答:2

我在项目中大量使用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;
}

程序输出符合预期:

method 1
method 2
Done...

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

这两种方法在任何情况下都不同吗?

c++ sfinae
2个回答
26
投票
我已经看到方法2在stackoverflow中使用得更多,但是我更喜欢方法1。

18
投票
除了max66's answer,更喜欢方法2的另一个原因是,使用方法1,您可以(偶然地)将显式类型参数作为第二个模板参数传递,并完全击败SFINAE机制。这可能是由于输入错误,复制/粘贴错误或由于较大的模板机制而引起的疏忽。

#include <cstdlib> #include <type_traits> #include <iostream> // NOTE: foo should only accept T=int template <class T, class = std::enable_if_t<std::is_same_v<T, int>>> void foo(){ std::cout << "method 1" << std::endl; } int main(){ // works fine foo<int>(); // ERROR: subsitution failure, as expected // foo<double>(); // Oops! also works, even though T != int :( foo<double, double>(); return 0; }

© www.soinside.com 2019 - 2024. All rights reserved.