模板 class 中的变量模板 - 意外错误(可能是错误?)
Variable template in template class - unexpected error (possible bug?)
拥有:
struct Value
{
template<class T>
static constexpr T value{0};
};
(0)
ideone
template<typename TValue>
struct Something
{
void x()
{
static_assert(TValue::template value<int> == 0, "");
}
};
int main() { Something<Value>{}.x(); return 0; }
不使用 clang++ 3.6 编译。
error: cannot refer to variable template 'value' without a template argument list
不使用 g++ 5.2 编译。
error: ‘template constexpr const T Value::value’ is not a function template
(1)
ideone
同时使用 clang++ 和 g++ 进行编译。
struct Something
{
void x()
{
static_assert(Value::template value<int> == 0, "");
}
};
int main() { Something{}.x(); return 0; }
为什么(0)编译失败?
如果通过模板参数(在本例中为 TValue
)访问 变量模板 ,似乎会出现此问题。为 TValue
定义类型别名或使用 typename
关键字无法解决问题。
这是怎么回事?
这绝对是 gcc 和 clang 在将变量模板作为相关名称处理时的错误。我提交了gcc 67248 and clang 24473。
作为目前的解决方法,两个编译器都支持执行变量模板的旧方法,即如果您添加:
struct Value
{
template<class T>
static constexpr T value = 0;
template <typename T>
struct variable_template_ish {
static constexpr T value = Value::value<T>;
};
};
然后编译如下:
template<typename TValue>
struct Something
{
void foo() {
static_assert(TValue::template variable_template_ish<int>::value == 0, "");
}
};
int main() {
Something<Value>{}.foo();
}
我以前在用 c++ 创建模板 class 头文件时遇到过一些麻烦。
确保 static constexpr T value{0};
的实现与声明在同一个头文件中。
拥有:
struct Value
{
template<class T>
static constexpr T value{0};
};
(0) ideone
template<typename TValue>
struct Something
{
void x()
{
static_assert(TValue::template value<int> == 0, "");
}
};
int main() { Something<Value>{}.x(); return 0; }
不使用 clang++ 3.6 编译。
error: cannot refer to variable template 'value' without a template argument list
不使用 g++ 5.2 编译。
error: ‘template constexpr const T Value::value’ is not a function template
(1) ideone
同时使用 clang++ 和 g++ 进行编译。
struct Something
{
void x()
{
static_assert(Value::template value<int> == 0, "");
}
};
int main() { Something{}.x(); return 0; }
为什么(0)编译失败?
如果通过模板参数(在本例中为 TValue
)访问 变量模板 ,似乎会出现此问题。为 TValue
定义类型别名或使用 typename
关键字无法解决问题。
这是怎么回事?
这绝对是 gcc 和 clang 在将变量模板作为相关名称处理时的错误。我提交了gcc 67248 and clang 24473。
作为目前的解决方法,两个编译器都支持执行变量模板的旧方法,即如果您添加:
struct Value
{
template<class T>
static constexpr T value = 0;
template <typename T>
struct variable_template_ish {
static constexpr T value = Value::value<T>;
};
};
然后编译如下:
template<typename TValue>
struct Something
{
void foo() {
static_assert(TValue::template variable_template_ish<int>::value == 0, "");
}
};
int main() {
Something<Value>{}.foo();
}
我以前在用 c++ 创建模板 class 头文件时遇到过一些麻烦。
确保 static constexpr T value{0};
的实现与声明在同一个头文件中。