简体   繁体   中英

try to get the type of a expression in template with declval and decltype

I run into trouble by defining a data type as a result of an operation. In the following example I have to Instances of a template class which have the template type "int".

I expect that the following expression results to int, but it did not!

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

Here is the full example:

#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);
}   

results in the following error ( 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

declval<T> is a function. you have to call it, to form value expressions to give to decltype

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM