Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板参数的部分类型推断-可能吗?_C++_Templates_Types_Type Inference - Fatal编程技术网

C++ C++;模板参数的部分类型推断-可能吗?

C++ C++;模板参数的部分类型推断-可能吗?,c++,templates,types,type-inference,C++,Templates,Types,Type Inference,我有一种情况,我有这样的嵌套结构: struct A { struct B {}; }; template<typename T> void func(typename T::B item) {} int main() { A::B item; func(item); // Error here because "candidate template ignored: couldn't infer template argument 'T'"

我有一种情况,我有这样的嵌套结构:

struct A
{
    struct B
    {};
};
template<typename T>
void func(typename T::B item)
{}

int main()
{
    A::B item;
    func(item);   // Error here because "candidate template ignored: couldn't infer template argument 'T'"
    return 0;
}
我有一些模板代码需要知道外部类型(在本例中为“A”)。 因此,我试图编写一个模板函数来推断外部类型,它如下所示:

struct A
{
    struct B
    {};
};
template<typename T>
void func(typename T::B item)
{}

int main()
{
    A::B item;
    func(item);   // Error here because "candidate template ignored: couldn't infer template argument 'T'"
    return 0;
}
模板
void func(类型名T::B项)
{}
int main()
{
A::B项目;
func(item);//此处出错,因为“已忽略候选模板:无法推断模板参数“t”
返回0;
}
它没有编译,原因在上面的注释中给出


现在,我当然可以将模板简化成这样,但是正如您在下面看到的,它不能满足我了解“outer”类型的要求,即A

template<typename T>
void func(typename T item)
{
    // Oops, I now have the complete type of A::B but I have a
    // specialized function that needs the A without the B as the type parameter
    someOtherFunc<???>(...);   // The ??? needs to be type A only, without the B
}
模板
void func(类型名称T项)
{
//哦,我现在有了A::B的完整类型,但我有一个
//需要A而不需要B作为类型参数的专用函数
someOtherFunc(…);//只需要类型A,不需要类型B
}

您可以添加一个
类型定义一个outerType到您的B班。
那么func的实现可能是:

#include <iostream>

struct A{
struct B {
    typedef A outerType;
};
};

template <class T>
void func( T f)
{
    typedef typename T::outerType outerType;
    outerType a;
    someotherfunc(a);
}   

int main ()
{
    A::B item;
    func(item);

    return 0;
}
#包括
结构A{
结构B{
typedef外部类型;
};
};
模板
无效函数(tf)
{
typedef typename T::outerType outerType;
外型a;
其他功能(a);
}   
int main()
{
A::B项目;
func(项目);
返回0;
}
当然,您拥有的每个内部类都应该将其外部类型命名为outerType,以使func计算出外部类型。

看看这个:。