仅当变量在 C++ 中可转换时,如何将变量从 int 转换为模板参数
How to convert a variable from an int into a template parameter only if it is convertable in c++
我正在尝试编写一个函数,它采用任意类型的变量并将其设置为 int
值,前提是给定变量的类型可以转换为 int
。我的简化代码:
template <typename T>
void getInt(T& param)
{
int int_value = calculate_int_value();
if(std::is_convertible_v<int, T>){
param = static_cast<T>(int_value);
}
}
但是,当我尝试编译它时,出现了诸如
之类的错误
error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(int&)'
error: invalid conversion from 'int' to 'const char*'
这让我觉得我不能只在 if
语句中转换任意类型的 int
值,这证明了它的可转换性。我如何实现我的目标?我错过了什么吗?
std::is_convertible_v
是在 C++17 中添加的,如果你的代码使用它那么这意味着你的编译器支持 C++17,它也有 if constexpr
:
if constexpr(std::is_convertible_v<int, T>){
param = static_cast<T>(int_value);
}
在常规 if
中,即使它总是求值为 false
,if
语句中的任何内容都必须仍然是有效的 C++。即使从未执行常规 if
语句的主体,它仍然必须编译为有效的 C++。当证明不能转换为 int
时,尝试将其转换为 int
当然是行不通的。
if constexpr
可以做其他事情(只要 if
本身是一个编译时常量表达式)。 if
语句的主体在语法上仍然必须是有效的 C++,但仅在语法上有效。
我正在尝试编写一个函数,它采用任意类型的变量并将其设置为 int
值,前提是给定变量的类型可以转换为 int
。我的简化代码:
template <typename T>
void getInt(T& param)
{
int int_value = calculate_int_value();
if(std::is_convertible_v<int, T>){
param = static_cast<T>(int_value);
}
}
但是,当我尝试编译它时,出现了诸如
之类的错误error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(int&)'
error: invalid conversion from 'int' to 'const char*'
这让我觉得我不能只在 if
语句中转换任意类型的 int
值,这证明了它的可转换性。我如何实现我的目标?我错过了什么吗?
std::is_convertible_v
是在 C++17 中添加的,如果你的代码使用它那么这意味着你的编译器支持 C++17,它也有 if constexpr
:
if constexpr(std::is_convertible_v<int, T>){
param = static_cast<T>(int_value);
}
在常规 if
中,即使它总是求值为 false
,if
语句中的任何内容都必须仍然是有效的 C++。即使从未执行常规 if
语句的主体,它仍然必须编译为有效的 C++。当证明不能转换为 int
时,尝试将其转换为 int
当然是行不通的。
if constexpr
可以做其他事情(只要 if
本身是一个编译时常量表达式)。 if
语句的主体在语法上仍然必须是有效的 C++,但仅在语法上有效。