是否有可能从函数返回一个类型作为返回类型
并将其用作成员变量,如下所示:
constexpr type myFunction(int a, int b){
if(a + b == 8) return int_8t;
if(a + b == 16) return int_16t;
if(a + b == 32) return int_32t;
return int_64t;
}
template<int x, int y>
class test{
using type = typename myFunction(x, y);
private:
type m_variable;
};
当在 Qt 中尝试这个例子时,它说
Error: 'constexpr' does not name a type
Error: 'test' is not a template type
class test{
^
在之前的问题中,有人向我展示了http://en.cppreference.com/w/cpp/types/conditional http://en.cppreference.com/w/cpp/types/conditional此功能,但仅适用于 2 种类型。
您无法使用普通函数来执行此操作。然而,使用模板元编程可以轻松完成。这种模板有时称为类型函数.
#include <cstdint>
template<int bits> struct integer { /* empty */ };
// Specialize for the bit widths we want.
template<> struct integer<8> { typedef int8_t type; };
template<> struct integer<16> { typedef int16_t type; };
template<> struct integer<32> { typedef int32_t type; };
可以这样使用。
using integer_type = integer<16>::type;
integer_type number = 42;
记得先integer<T>::type
与typename
关键字如果T
本身就是一个模板参数。
我将其作为练习,将其扩展为接受两个整数作为参数并根据两者之和返回适当类型的模板。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)