c++ - 如何在 C++ 的另一个模板函数中使用属于模板类的嵌套类型?

标签 c++ templates compiler-errors inner-classes

我正在设置一个根据元组类型和仿函数结构初始化元组的函数 For有一个 size_t 模板参数 INDEX保留编译时索引。这个仿函数也可能依赖于其他模板参数 T... .因此,仿函数存在于保存这些模板参数的其他结构中(本例中为 TClass)。

初始化函数(这里称为Bar)有一个template<std::size_t> class模板参数以确保使用的类实际上可以存储索引。

虽然我提出的设计在我从非模板函数调用它时工作正常,但如果模板 T2 则它不会编译。一个函数确实决定了包装器的模板参数 TClass .

这里是仿函数 For 的定义包在里面 TClass :

#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 的编译器输出-电话是:

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
}

显然,在类型模板由函数的模板参数确定的函数中使用依赖类型名称是不可能的,但为什么呢?我该如何正确实现呢?为了使将来使用类型特征编写类型检查更容易,我希望可以使用仿函数。

最佳答案

编译器无法知道 TClass<T>::For指模板实例化第一阶段的模板。它需要一点帮助 template关键词。修复:

template <typename T> void foo() {  
    bar<TClass<T>::template For>(); 
}

关于c++ - 如何在 C++ 的另一个模板函数中使用属于模板类的嵌套类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512721/

相关文章:

c++ - 函数模板 - 编译器在使用相同类型调用时选择具有不同参数类型的函数

Angular - 安装库 fullcalendar 时出错

excel - VBA 代码返回 if 语句的编译错误

c++ - Boost Gil 能够光栅化字体吗?

c++ - 无法解析类型 '',模板类型

c++ - 如何在模板中定义迭代器?

symfony - 商店 6 : Twig files not loaded when using sw_include

python - 尝试用Python中的正则表达式替换\t为\s,但结果出现 "Unhashable type:list"错误

c++ - std::shared_ptr 什么时候释放它的对象?

c++ - 错误 : 'Qt::ConnectionType' is not a class or namespace