繁体   English   中英

函数C ++中具有大小返回类型的模板?

[英]Template with sized return type in function C++?

是否可以以这种方式设计模板功能

template <typename T1, typename T2>
T3 f(T1 x, T2 y);

其中如果sizeof(T1) > sizeof(T2)T3 = T1 ,否则T3 = T2

进一步要求......

我试图定义类似的东西:

template <int i>
struct A {
    int a;
};

template <int j>
struct B {
    int b;
};

template <int i, int j>
typename std::conditional< i > j , A<i>, B<j> >::type
func() {
    ;
}

但是当我尝试编译时......

Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -o main.o "..\\main.cc" 
In file included from ..\main.cc:8:0:
..\header.h:34:30: error: wrong number of template arguments (1, should be 3)
 typename std::conditional< i > j , A<i>, B<j> >::type
                              ^
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\move.h:57:0,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_pair.h:59,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_algobase.h:64,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\char_traits.h:39,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ios:40,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ostream:38,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\iostream:39,
                 from ..\header.h:11,
                 from ..\main.cc:8:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\type_traits:77:12: error: provided for 'template<bool <anonymous>, class, class> struct std::conditional'
     struct conditional;
            ^
In file included from ..\main.cc:8:0:
..\header.h:34:32: error: 'j' in namespace 'std' does not name a type
 typename std::conditional< i > j , A<i>, B<j> >::type
                                ^
..\header.h:34:34: error: expected unqualified-id before ',' token
 typename std::conditional< i > j , A<i>, B<j> >::type

所以在这种情况下基本上不起作用......(非类型模板)。

你可以使用std::conditional

template <typename T1, typename T2>
typename std::conditional< (sizeof(T1) > sizeof(T2)),
                  T1, T2 >::type
f(T1 x, T2 y);

如果你想,你可以这样解决这个问题:

template <typename T1, typename T2>
using largest_type = 
    typename std::conditional< (sizeof(T1) > sizeof(T2)),
                               T1, T2 >::type;

template <typename T1, typename T2>
largest_type<T1,T2>
f(T1 x, T2 y);

largest_type写为可变参数模板largest_type练习:D

这是一个令人烦恼的解析!

typename std::conditional< i > j , A<i>, B<j> >::type
//                           ^
//                           Looks like the close of template params

把表格放在表达式上:

typename std::conditional< (i > j) , A<i>, B<j> >::type

或扭转条件:

typename std::conditional< j < i , A<i>, B<j> >::type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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