c++ - 将不同类型的参数传递给函数模板

标签 c++ function templates

考虑这个模板:

template<typename t>
t add(t a, t b) {
    return a+b;
}

我怎样才能传递不同类型的参数,所以返回值是:

  • int 如果两个参数都是 int 类型。

  • float 如果参数之一是 float 类型。

  • float 如果两个参数都是 float 类型。

我也尝试过为模板设置多个参数:

template<typename t, typename c>

将它们用于函数参数,以便它们可以不同(t add(t a, c b))但我无法理解的是如何更改函数的类型( int、float、double 等)取决于返回类型?

最佳答案

你想要的是 std::common_type :

template<typename T0, typename T1>
typename std::common_type<T0, T1>::type add(T0 a, T1 b) {
    return a+b;
}

文档说明:

For arithmetic types, the common type may be viewed as the type of the (possibly mixed-mode) arithmetic expression such as T0() + T1() + ... + Tn().

但是,正如@Jarod42 在评论中指出的那样,这只是一个观点,在某些情况下可能是错误的:例如,std::common_type<char, char>::typechar而算术表达式 char() + char()产量 int .


更完整的实现可能会显式转换结果以消除上述情况下可能出现的警告:

template<typename T0, typename T1, typename R = std::common_type_t<T0, T1>>
R add(T0 a, T1 b) {
    return static_cast<R>(a+b);
}

这里 std::common_type默认情况下用于返回类型,但由于它是模板参数,因此您可以在使用函数时指定不同的类型(可能在更复杂的用例中有用):

char a = 1, b = 2;
add<decltype(a), decltype(b), int>(a, b);

使用 std::conditional std::is_same ,@Jarod42 在评论中提出的更完整的解决方案允许拥有模板 R作为第一个参数,并保持自动扣除ab :

template <typename R, typename T0, typename T1>
using ResType = std::conditional_t<
    std::is_same<void, R>::value,
    std::common_type_t<T0, T1>, // default
    R                           // R was explicitly specified: use it
>;

template <typename R = void, typename T0, typename T1>
ResType<R, T0, T1> add(T0 a, T1 b)
{
    return static_cast<ResType<R, T0, T1>>(a + b);
}

用法:

char a = 1, b = 2;
add(a, b);       // returns char
add<int>(a, b);  // returns int

关于c++ - 将不同类型的参数传递给函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320269/

相关文章:

c++ - 从 ustring 获取子串

c++ - 这些初始化有什么区别?

c++ - 如何为枚举和特定类型专门化模板函数?

python - 将变量直接分配给Python中的函数

c++ - 使用 C++ 模板的 TDD 技术

C++ 模板 : "type/value mismatch at argument" and "expected a constant type of int, got int"

c++ - 我在 Clang 和 GCC 中发现了错误吗?

c++ - 将指针传递给 C++ 中的方法导致奇怪的输出

java - 如何从 2 个函数中获取字符并产生输出?

c++ - 如何在表示整数数据结构的类上定义函数