简体   繁体   English

如何包括不是参数的c ++模板类型

[英]how to include c++ template types that are not parameters

I want to have a type in a template like T_signed in the code below 我想在下面的代码中在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;
}

While the above is a simplification of the actual code I am writing and greatly believe it is what is preventing the code from compiling. 虽然上面是我正在编写的实际代码的简化,但我坚信这是阻止代码编译的原因。 How do I get the the compiler to figure out the type of T_signed implicitly based on what the type input is? 我如何让编译器根据输入的类型隐式地找出T_signed的类型? Any help appreciated. 任何帮助表示赞赏。

Something like this , using std::make_signed : 使用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;
}

You can also add std::enable_if or static_assert to ensure that the passed in type really is unsigned. 您还可以添加std :: enable_ifstatic_assert以确保传入的类型确实是未签名的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM