拥有:
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; }
错误:如果没有模板参数列表,则无法引用变量模板'value‘
错误:‘template constexpr const T value::value’不是函数模板
(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
关键字不能解决此问题。
这里发生了什么事?
发布于 2015-08-17 20:55:01
这肯定是gcc和clang在将变量模板作为依赖名称处理时的一个错误。我提交了gcc 67248和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();
}
发布于 2015-08-17 20:57:35
我以前在c++中创建模板类头文件时遇到过一些令人头疼的问题。
确保static constexpr T value{0};
的实现与声明在同一个头文件中。
https://stackoverflow.com/questions/32050119
复制相似问题