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

时间:2015-09-24 14:59:37

标签: c++ templates variables storage

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

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

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

2 个答案:

答案 0 :(得分:15)

您可以使用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写为可变参数模板留作练习:D

答案 1 :(得分:2)

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

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