【发布时间】:2019-08-26 00:28:05
【问题描述】:
我正在设置一个函数,该函数基于元组类型和函子结构 For 初始化元组,该函子结构具有 size_t 模板参数 INDEX 以保留编译时索引。这个函子也可能依赖于其他模板参数T...。因此,函子存在于保存这些模板参数的其他结构中(本例中为TClass)。
初始化函数(这里称为Bar)有一个template<std::size_t> class模板参数,以确保使用的类实际上可以存储索引。
虽然当我从非模板函数调用它时,我提出的设计工作正常,但如果函数的模板T2 确实确定了包装器TClass 的模板参数,则它不会编译。
这是包裹在TClass中的函子For的定义:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> struct For {
void operator()() {}
};
};
这是我想使用的函数调用:
template <template<std::size_t> class FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>::For>(); //Does not compile
}
int main() {
bar<TClass<int>::For>(); //Works
foo<int>();
return 0;
}
错误的foo-call 的编译器输出是:
error: dependent-name ‘TClass<T>::For’ is parsed as a non-type, but instantiation yields a type
Bar<TClass<T>::For>(); //Does not compile
我知道依赖类型名称通常必须以typename 开头,但这对于第一个bar 调用也不是必需的。我认为这是因为模板参数只能解释为一种类型。所以我认为typename 可能会导致正确编译,但如果我将foo 更改为
template <typename T> void foo() {
bar<typename TClass<T>::For>(); //Does not compile
}
我明白了:
error: ‘typename TClass<int>::For’ names ‘template<long unsigned int INDEX> struct TClass<int>::For’, which is not a type
Bar<typename TClass<T>::For>(); //Does not compile
我还提出了一个设计,其中TClass 的() 运算符依赖于模板INDEX,它也可以正常工作,因为不再需要使用嵌套类型。它看起来像这样:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> void operator()() {}
};
template <typename FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>>(); //Does compile
}
显然,在类型的模板由函数的模板参数确定的函数中,不可能使用依赖类型名称,但为什么呢?以及如何正确实施?为了使将来使用类型特征编写类型检查更容易,如果我可以使用仿函数,我会更喜欢它。
【问题讨论】:
标签: c++ templates compiler-errors inner-classes