在一行中将默认类型值的指针作为参数传递
Pass a pointer on default typed value as argument in one line
如何将指向特定类型的默认值的指针作为参数传递?
我的函数期望:
void my_function(void* value);
这项工作:
auto value = int8_t();
my_function(&value);
这行不通:
my_function(&int8_t());
同样如此:
my_function(&(int8_t()));
如何在一行中传递指向特定类型(在我的示例中为int8_t
)的默认值的指针?
你不能只得到一个临时地址,所以它对你不起作用。相反,您可以创建一个辅助模板函数来 return 所需类型的默认值:
template <typename T>
const T *defval()
{
static const T value;
return &value;
}
实际上这意味着,编译器将为您在代码中 defval
函数中使用的每种类型生成一个 static
默认变量。所以,这正是您想要的。
然后你可以像这样使用它:
my_function(defval<int8_t>());
但是请注意,您应该将 my_function
的签名更改为:
void my_function(const void* value);
此处需要 const
以保证模板函数中的内部 static
值不会更改,并将保持默认值。
所以,最终代码是:
void my_function(const void *value)
{
(void)value;
}
template <typename T>
const T *defval()
{
static const T value;
return &value;
}
int main()
{
my_function(defval<int8_t>());
return 0;
}
如何将指向特定类型的默认值的指针作为参数传递?
我的函数期望:
void my_function(void* value);
这项工作:
auto value = int8_t();
my_function(&value);
这行不通:
my_function(&int8_t());
同样如此:
my_function(&(int8_t()));
如何在一行中传递指向特定类型(在我的示例中为int8_t
)的默认值的指针?
你不能只得到一个临时地址,所以它对你不起作用。相反,您可以创建一个辅助模板函数来 return 所需类型的默认值:
template <typename T>
const T *defval()
{
static const T value;
return &value;
}
实际上这意味着,编译器将为您在代码中 defval
函数中使用的每种类型生成一个 static
默认变量。所以,这正是您想要的。
然后你可以像这样使用它:
my_function(defval<int8_t>());
但是请注意,您应该将 my_function
的签名更改为:
void my_function(const void* value);
此处需要 const
以保证模板函数中的内部 static
值不会更改,并将保持默认值。
所以,最终代码是:
void my_function(const void *value)
{
(void)value;
}
template <typename T>
const T *defval()
{
static const T value;
return &value;
}
int main()
{
my_function(defval<int8_t>());
return 0;
}