【发布时间】:2018-07-20 21:54:43
【问题描述】:
我需要使用静态成员变量模板foo::static_variable_template<T> 定义一个类foo。只有当T 满足某些要求时,该成员才应该存在。例如,当 constexpr 静态函数 T::constexpr_static_function() 存在时。否则,foo::static_variable_template<T> 不应该存在。此外,我希望能够在编译时通过 SFINAE 测试 foo::static_variable_template<T> 的存在。
这是我想做的一个近似值:
#include <iostream>
struct foo
{
template<class T>
static constexpr int static_variable_template =
T::constexpr_static_function();
// XXX this works but requires a second defaulted template parameter
// template<class T, int = T::constexpr_static_function()>
// static constexpr int static_variable_template =
// T::constexpr_static_function();
};
struct has_constexpr_static_function
{
static constexpr int constexpr_static_function() { return 42; }
};
struct hasnt_constexpr_static_function
{
};
template<class T, class U,
int = T::template static_variable_template<U>>
void test_for_static_variable_template(int)
{
std::cout << "yes it has\n";
}
template<class T, class U>
void test_for_static_variable_template(...)
{
std::cout << "no it hasn't\n";
}
int main()
{
test_for_static_variable_template<foo, has_constexpr_static_function>(0);
test_for_static_variable_template<foo, hasnt_constexpr_static_function>(0);
}
这种近似值几乎可行,但前提是foo::static_variable_template 有第二个默认模板参数。因为这第二个参数是一个实现细节,所以我想在foo::static_variable_template 的公共接口中隐藏它。
这在 C++17 中可行吗?
【问题讨论】:
-
你不能让特征依赖于
constexpr_static_function并检查吗?
标签: c++ templates template-meta-programming sfinae