类型作为returntype在c ++ [英] type as returntype in c++
问题描述
有可能从函数
中返回一个类型作为returntype,并使用类似这样的成员变量:
Is there a possibility to return a type as a returntype from a function and use it for a member variable using something like this:
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中尝试这个例子时,它说
When trying this example in Qt it says
Error: 'constexpr' does not name a type
Error: 'test' is not a template type
class test{
^
在先前的问题中,有人向我显示 http://en.cppreference.com/w/cpp/types/conditional 这个函数,但它只适用于2种类型。
In an earlier question someone showed me http://en.cppreference.com/w/cpp/types/conditional this function, but it works only for 2 Types.
推荐答案
你不能用普通的函数做到这一点。然而,它很容易使用模板元编程。这种模板有时称为类型函数。
You cannot do this with a normal function. However, it is easily done using template meta-programming. This kind of template is sometimes called a type function.
#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;
请记住整数< T> :: type
c> typename
关键字if T
本身是一个模板参数。
Remember to precede integer<T>::type
with the typename
keyword if T
is itself a template parameter.
我把它作为一个练习,扩展到一个模板,接受两个整数作为参数,并返回基于两者之和的合适的类型。
I leave it as an exercise to you to extend this to a template that accepts two integers as parameters and returns the appropriate type based on the sum of the two.
这篇关于类型作为returntype在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!