【问题标题】:C++ partial type inference for template parameter - Is it possible?模板参数的 C++ 部分类型推断 - 有可能吗?
【发布时间】:2014-07-31 14:18:01
【问题描述】:

我有这样的嵌套结构:

struct A
{
    struct B
    {};
};

我有一些模板代码需要知道 OUTER 类型(在本例中为“A”)。 所以我正在尝试编写一个可以推断外部类型的模板函数,它看起来像这样:

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)的要求。

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
}

【问题讨论】:

标签: c++ templates types type-inference


【解决方案1】:

您可以在 B 类中添加 typedef A outerType;
那么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;
}

那么当然,你拥有的每个内部类都应该将其外部类型命名为outerType,以使func计算出外部类型。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多