typedef 模板参数推导失败? [重复]

问题描述 投票:0回答:3

考虑以下几类:

template <typename T1, typename T2>
class A{ 
public:
    // ...
};

template<typename _T>
struct alias { typedef A<int,_T> intA; };

class B{
public:
    // ...
    template <typename _T> B& operator=(const typename alias<_T>::intA& _arg) { };
};

当我尝试将

A<int,int>
类的对象分配给
B
类的对象时,出现以下编译错误:

template argument deduction/substitution failed:   couldn't deduce template parameter ‘_T’

是否有另一种方法可以使用 typedef 的某些内容作为

B::operator=()
??

的输入参数
c++ class templates typedef
3个回答
2
投票

模板化

using
可能会解决问题

template <typename T1, typename T2>
class A{ 
public:
    // ...
};

template<typename _T>
using alias = A<int,_T>;

class B{
public:
    // ...
    template <typename _T> B& operator=(const alias<_T>& ) { return *this; };
};

void f()
{
    B b;
    A<int, int> a;
    b = a;
}

2
投票

问题在于

intA
是一个从属名称。无法从从属名称推断出模板。例如,请参阅:依赖类型:模板参数推导失败

您还缺少

typename
关键字。

您可以显式指定运算符的类型:

template <typename T1, typename T2>
struct A{ };

template<typename _T>
struct alias { typedef A<int,_T> intA; };

struct B 
{
    template <typename T> B& operator=(const typename alias<T>::intA& _arg) { };
};

int main() 
{
    A<int,int> a;
    B b;
    b.operator=<int>(a);
    return 0;
}

或者您可以使用模板化别名(带或不带函数)来拥有特定的、非依赖名称参数:

template <typename T1, typename T2>
struct A{ };

template<class T>
using alias_int = A<int, T>;

struct alias
{
    template<class T>
    using intA = A<int, T>;
};

struct B 
{
    template <typename T> B& operator=(const alias_int<T>& _arg) { };
};

struct C
{
    template <typename T> C& operator=(const alias::intA<T>& _arg) { };
};

int main() 
{
    A<int,int> a;
    B b;
    C c;
    b = a;
    c = a;
    return 0;
}

0
投票

我遇到了不同的错误(使用 g++ 5.4):

need ‘typename’ before ‘alias<_T>::intA’ because ‘alias<_T>’ is a dependent scope
确实,以下内容对我来说是正确的:

template <typename T1, typename T2>
class A{ 
public:
    // ...
};

template<typename _T>
struct alias { typedef A<int,_T> intA; };

class B{
public:
    // ...
    template <typename _T> B& operator=(const typename alias<_T>::intA& _arg) { };
};

我认为原因是

alias<_T>::intA
不是实际类型,而是模板化类型名。

© www.soinside.com 2019 - 2024. All rights reserved.