enable_if 在构造函数上

enable_if on constructor

我有以下代码。我想在枚举类型上模板化 class 和 class 构造函数。但是,这段代码不起作用?我怎样才能达到我想要的?

#include < iostream >

#include < type_traits >

enum class MyType
{
    Positive,
    Negative
};

template < MyType T >

struct B {

    int val = 0;

    template<typename U = T>
    B(int n, typename std::enable_if<U==MyType::Positive>::type* = 0) : val(n) { };

    template<typename U = T>
    B(int n, typename std::enable_if<U==MyType::Negative>::type* = 0) : val(-n) { };
};

int main() {

    B<MyType::Positive> y(10);

    B<MyType::Negative> n(10);
}

你的模板有一个 typename 参数,但你想要你的枚举作为参数。让我们解决这个问题:

#include <iostream>
#include <type_traits>

enum class MyType
{
    Positive,
    Negative
};

template <MyType T>
struct B {
    int val = 0;

    template<MyType U = T>
    B(int n, typename std::enable_if<U==MyType::Positive>::type* = 0) : val(n) { };

    template<MyType U = T>
    B(int n, typename std::enable_if<U==MyType::Negative>::type* = 0) : val(-n) { };
};

int main() {
    B<MyType::Positive> y(10);
    B<MyType::Negative> n(10);
}

此外,您可以将 SFINAE 表达式放在模板参数中以整理构造函数参数:

template<MyType U = T, typename std::enable_if<U == MyType::Positive, int>::type = 0>
B(int n) : val(n) { };

template<MyType U = T, typename std::enable_if<U == MyType::Negative, int>::type = 0>
B(int n) : val(-n) { };

你的问题是T是一个非类型模板参数,所以你不能typename U = T因为你想要U类型模板参数,默认为T,这是来自MyType.

的值

名称 T 选得非常糟糕,这可能是您一开始就犯了这个错误的原因。将 typename U = T 更改为 MyType U = T,您的代码将编译。

在 C++20 中,使用 requires:

甚至会更简单
enum class MyType
{
    Positive,
    Negative
};

template <MyType E>
struct B
{
    int val = 0;

    B(int n) requires(E == MyType::Positive) : val(n) {}
    B(int n) requires(E == MyType::Negative) : val(-n) {}
};