如何包含不是参数的 C++ 模板类型
how to include c++ template types that are not parameters
我想在下面的代码中像 T_signed 这样的模板输入类型
template <typename T_unsigned, typename T_signed> bool foo(T_unsigned input)
{
T_signed temp= ((T_signed) input)-100;
//use temp for calculations to figure out myBool
return myBool;
}
虽然以上是对我正在编写的实际代码的简化,但我坚信这是阻止代码编译的原因。如何让编译器根据输入的类型隐式确定 T_signed 的类型?任何帮助表示赞赏。
某事like this, using std::make_signed:
#include <iostream>
#include <type_traits>
template <typename Tu>
bool foo(Tu input) {
std::cout << std::is_signed<Tu>::value << std::endl;
typedef typename std::make_signed<Tu>::type Ts;
Ts temp = input - 100;
return (temp < 0);
}
int main() {
std::cout << foo(32u) << std::endl;
}
您还可以添加std::enable_if or static_assert以确保传入的类型确实是无符号的。
我想在下面的代码中像 T_signed 这样的模板输入类型
template <typename T_unsigned, typename T_signed> bool foo(T_unsigned input)
{
T_signed temp= ((T_signed) input)-100;
//use temp for calculations to figure out myBool
return myBool;
}
虽然以上是对我正在编写的实际代码的简化,但我坚信这是阻止代码编译的原因。如何让编译器根据输入的类型隐式确定 T_signed 的类型?任何帮助表示赞赏。
某事like this, using std::make_signed:
#include <iostream>
#include <type_traits>
template <typename Tu>
bool foo(Tu input) {
std::cout << std::is_signed<Tu>::value << std::endl;
typedef typename std::make_signed<Tu>::type Ts;
Ts temp = input - 100;
return (temp < 0);
}
int main() {
std::cout << foo(32u) << std::endl;
}
您还可以添加std::enable_if or static_assert以确保传入的类型确实是无符号的。