c++ - 相互组合多个模板

标签 c++ templates c++17

如何在一个函数中组合多种类型

template < typename T1 >
template < typename T2 >
T2 average( T1 v1, T1 v2, T1 v3 )
{
    T averageValue;
    cout<<"after averageValue; v1: "<<typeid(v1).name()
        <<" v2: "<<typeid(v2).name()
        <<" v3: "<<typeid(v3).name()
        <<" averageValue: "<<typeid(averageValue).name();
    averageValue =(v1+v2+v3)/.3;
    cout<<"\nAfter averageValue =(v1+v2+v3)/3; averageValue: "<<typeid(averageValue).name();
    return averageValue;
};

我知道代码不会编译,但我想知道是否有任何方法可以做到这一点

最佳答案

在 C++17 中,您可以使用 variadic templatefold expression结合sizeof...运算符(operator):

template<typename... Args>
auto average(Args&&...args)
{
    return (args + ...) / double(sizeof...(args));
}

关于c++ - 相互组合多个模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270440/

相关文章:

c++ - gcc 可以编译可变参数模板而 clang 不能

c++ - 来自函数模板的显式模板特化不起作用

c++ - 使用 if constexpr 的条件 constexpr 表达式

c++ - 无法在用户定义的类型上使用 std::apply

c++ - Qt5.6设置应用程序图标(Linux)

c++ - 为什么这种复制初始化(带有两次隐式转换)在GCC/Clang中不起作用?

c++ - OpenCV N channel 图像

c++ - 使用成员模板函数的显式模板实例化

c++ - 如何从 Http 请求处理程序正确终止 POCO ServerAPPLICATION

c++ - C++ 有安全的导航运算符吗?