尝试使用declval和decltype获取模板中表达式的类型

时间:2014-02-13 08:18:23

标签: c++ templates c++11

我通过定义操作结果的数据类型而遇到麻烦。 在下面的示例中,我需要具有模板类的实例 模板类型“int”。

我希望以下表达式导致int,但它没有!

typename A and B are both int
decltype( declval<A>+declval<B>)

以下是完整示例:

#include <utility>
using namespace std;


template <typename T>  
class AV
{   
};  

template <typename T>
class Term
{   
};  

template <class A, class B>
auto operator +( AV<A>& a, AV<B>& b )->Term< int >
{ 
    Term< decltype(declval<A>+declval<B>) >t(&a,&b);
    //             ~~~~~~~~~~~~~~~~~~~~~~   invalid operands of types
    //                        '<unresolved overloaded function type>
    return t;
}


int main()
{   
    AV<int> a;
    AV<int> b;

    Term<int> x(a+b);
}   

导致以下错误(gcc 4.8.2)

main.cpp: In instantiation of 'Term<int> operator+(AV<A>&, AV<B>&) [with A = int; B = int]':
main.cpp:47:23:   required from here
main.cpp:39:111: error: invalid operands of types '<unresolved overloaded function type>' and '<unresolved overloaded function type>' to binary 'operator+'
     template <class A, class B> auto operator +( AV<A>& a, AV<B>& b )->Term< int > { Term< decltype(declval<A>+declval<B>) >t(&a,&b); return t; }
                                                                                                               ^
main.cpp:39:111: error: invalid operands of types '<unresolved overloaded function type>' and '<unresolved overloaded function type>' to binary 'operator+'
make: *** [go] Error 1

1 个答案:

答案 0 :(得分:4)

declval<T>是一个功能。你必须调用它,形成值表达式以赋予decltype

Term< decltype(declval<A>()+declval<B>()) >t(&a,&b);
相关问题