条件表达式中的C++sizeof(typename T)

C++ sizeof( typename T) in a conditional expression

本文关键字:typename C++sizeof 表达式 条件      更新时间:2023-10-16

我在这里问了一个问题,C++模板参数和表达式,得到了答案,但现在我想转到这样的问题上:

#include <complex>
#include <type_traits>
using namespace std;
template<class T, class U>
complex< conditional<(sizeof( T ) > sizeof( U )), T, U>::type > my_method(T x, U y)  { }


这给了我错误:

main.cpp:10:65: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp> struct std::complex’
main.cpp:10:65: error:   expected a type, got ‘std::conditional<(sizeof (T) > sizeof (U)), int, float>::type’


我尝试在T和U之前添加关键字typename和class,但这也改变了错误:

main.cpp:37:1: error: wrong number of template arguments (1, should be 3)
/usr/include/c++/4.7/type_traits:77:12: error: provided for ‘template<bool <anonymous>, class, class> struct std::conditional’
main.cpp:10:10: error: template argument 1 is invalid
main.cpp:10:1: error: expected unqualified-id at end of input


我在linux上使用带有-std=c++11的g++作为编译器选项。有没有办法做我想做的事?谢谢

正如编译器所说:

main.cpp:10:65: error:   expected a type, got ‘std::conditional<(sizeof (T) > sizeof (U)), int, float>::type’

std::conditional<...之前缺少类型名。