【发布时间】:2019-10-18 16:35:55
【问题描述】:
我查看了一些类似的问题,例如 this one 和 this other one,并且我了解如何使用 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";
}
在此先感谢,感谢任何帮助/指导!
【问题讨论】:
-
无法通过
enable_if控制变量的存在 -
在此之前,您只能在类级别进行编写以获取变量。尽管这是一个有趣的命题,但在 C++ 20 中通过
requires有条件地包含一个变量。我认为我们不会有任何 ODR 违规,而且会很方便。 -
“替换失败不是错误”(或
SFINAE),仅限applies during overload resolution of function templates。显然成员变量不是这种情况......