Reputation: 2732
Is it possible to design a template function in such a way
template <typename T1, typename T2>
T3 f(T1 x, T2 y);
where if sizeof(T1) > sizeof(T2)
then T3 = T1
, otherwise T3 = T2
Further request...
I tried to define something like:
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() {
;
}
But when i try to compile ...
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
So basically doesn't work in that case... (non type templates).
Upvotes: 3
Views: 144
Reputation: 30909
It's a vexing parse!
typename std::conditional< i > j , A<i>, B<j> >::type
// ^
// Looks like the close of template params
Put parens around the expression:
typename std::conditional< (i > j) , A<i>, B<j> >::type
or reverse the condition:
typename std::conditional< j < i , A<i>, B<j> >::type
Upvotes: 2
Reputation: 65720
You can use std::conditional
:
template <typename T1, typename T2>
typename std::conditional< (sizeof(T1) > sizeof(T2)),
T1, T2 >::type
f(T1 x, T2 y);
If you wanted, you could factor this out like so:
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);
Writing largest_type
as a variadic template is left as an exercise :D
Upvotes: 15