是否有可能将类型作为函数的返回类型返回,并将其用于成员变量,使用以下内容:
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;
};
Run Code Online (Sandbox Code Playgroud)
在 Qt 中尝试此示例时,它说
Error: 'constexpr' does not name a type
Error: 'test' is not a template type
class test{
^
Run Code Online (Sandbox Code Playgroud)
在之前的一个问题中,有人向我展示了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; };
Run Code Online (Sandbox Code Playgroud)
它可以像这样使用。
using integer_type = integer<16>::type;
integer_type number = 42;
Run Code Online (Sandbox Code Playgroud)
记住在关键字之前integer<T>::type加上typenameifT本身就是一个模板参数。
我把它作为一个练习留给你,把它扩展到一个模板,它接受两个整数作为参数,并根据两者的总和返回适当的类型。
| 归档时间: |
|
| 查看次数: |
955 次 |
| 最近记录: |