std :: enable_if для изменения члена * переменная * объявление / тип - PullRequest
2 голосов
/ 18 октября 2019

Я посмотрел на несколько похожих вопросов, например , этот и , этот другой , например, и я понимаю, как работать с enable_if для члена функции .

Вот рабочий пример:

#include <iostream>

template <int size>
class Test
{
private:
    constexpr static bool ENABLE = (size < 10);

public:
    template <bool E = ENABLE, typename std::enable_if<E, int>::type = 0>
    static int foo();

    template <bool E = ENABLE, typename std::enable_if<!E, int>::type = 0>
    constexpr static int foo();
};

template <int size>
template <bool E, typename std::enable_if<E, int>::type>
int Test<size>::foo()
{
    return 7;
}

template <int size>
template <bool E, typename std::enable_if<!E, int>::type>
constexpr int Test<size>::foo()
{
    return 12;
}

int main()
{
    Test<5> v1;
    Test<15> v2;

    std::cout << v1.foo() << "\n";
    std::cout << v2.foo() << "\n";
}

Однако, когда я пытаюсь немного изменить код для работы с переменными , я получаю неприятные ошибки объявления,Можно ли это вообще сделать с переменными, я просто что-то упускаю?

Вот мой проблемный пример кода:

#include <iostream>

template <int size>
class Test
{
private:
    constexpr static bool ENABLE = (size < 10);

public:
    template <bool E = ENABLE, typename std::enable_if<E, int>::type = 0>
    static int foo;

    template <bool E = ENABLE, typename std::enable_if<!E, int>::type = 0>
    constexpr static int foo = 12;
};

template <int size>
template <bool E, typename std::enable_if<E, int>::type>
int Test<size>::foo = 7;

template <int size>
template <bool E, typename std::enable_if<!E, int>::type>
constexpr int Test<size>::foo;

int main()
{
    Test<5> v1;
    Test<15> v2;

    std::cout << v1.foo<> << "\n";
    std::cout << v2.foo<> << "\n";
}

Заранее спасибо, любая помощь / руководство приветствуется!

Ответы [ 2 ]

5 голосов
/ 18 октября 2019

Вы можете достичь желаемого эффекта с помощью условного базового класса, который предоставляет член foo:

template<int FOO_INIT>
struct TestImpl1 {
    static int foo;
};

template<int FOO_INIT>
int TestImpl1<FOO_INIT>::foo = FOO_INIT;

template<int FOO_INIT>
struct TestImpl2 {
    constexpr static int foo = FOO_INIT;
};

template<int FOO_INIT>
constexpr int TestImpl2<FOO_INIT>::foo;

template<int size>
struct Test
    : std::conditional<
        (size < 10),
        TestImpl1<7>,
        TestImpl2<12>
      >::type
{};

int main() {
    Test<5> v1;
    Test<15> v2;

    std::cout << v1.foo << "\n";
    std::cout << v2.foo << "\n";

    // constexpr int i1 = v1.foo; // Fails to compile because Test<5>::foo is not constexpr.
    constexpr int i2 = v2.foo; // Compiles because Test<15>::foo is constexpr.
}
0 голосов
/ 18 октября 2019

Если вы делаете это только со статическими переменными-членами, все равно есть шанс, что вы сможете заставить их работать, используя статические переменные в области блока. Таким образом, ваш foo становится функцией, поэтому вы можете применять к ним SFINAE.

#include <iostream>

template <int size>
class Test
{
private:
    constexpr static bool ENABLE = (size < 10);

public:
    template <bool E = ENABLE, typename std::enable_if<E, int>::type = 0>
    static int& foo();

    template <bool E = ENABLE, typename std::enable_if<!E, int>::type = 0>
    constexpr static int foo();
};

template <int size>
template <bool E, typename std::enable_if<E, int>::type>
int& Test<size>::foo() {
    static int foo_impl = 7;
    return foo_impl;
}

template <int size>
template <bool E, typename std::enable_if<!E, int>::type>
constexpr int Test<size>::foo() {
    return 12;
}

int main()
{
    Test<5> v1;
    Test<15> v2;

    std::cout << v1.foo() << "\n";
    std::cout << v2.foo() << "\n";
}

Демонстрационная версия

...