具有多个包的c++模板,通过参数和返回值进行推导

标签 c++ templates c++11

我对 C++ 如何解释以下代码感到有点困惑:

template<class ... ReturnTypes, class ... ParameterTypes>
std::tuple<ReturnTypes...> Method(const ParameterTypes & ... Parameters)
{
    (...)
};

编译以下代码时:

std::tuple<unsigned int> R = Object.Method<unsigned int, unsigned int>(10);

我得到:

error: conversion from 'std::tuple<unsigned int, unsigned int>' to non-scalar type 'std::tuple<unsigned int>' requested
  std::tuple<unsigned int> R = Object.Method<unsigned int, unsigned int>(10);

是否有可能创建一个具有两个参数包的模板方法(在非模板类中)——一个用于返回类型(在元组中),一个用于参数类型?

最佳答案

可以使用template模板参数来区分这两个参数包:

#include <tuple>

template <class... T> struct typelist { };

template <typename... ReturnTypes,
          template <typename...> class T,
          class ... ParameterTypes>
std::tuple<ReturnTypes...> Method(T<ReturnTypes...>,
                                  const ParameterTypes & ... Parameters)
{
    return std::tuple<ReturnTypes...>();
};

int main()
{
    using ReturnTypes = typelist<int, char>;
    auto t = Method(ReturnTypes{}, 10, "hello", false);

    static_assert(std::is_same<decltype(t), std::tuple<int,char>>{}, "types do not match");
    return 0;
}

live on ideone

关于具有多个包的c++模板,通过参数和返回值进行推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905340/

相关文章:

c++ - 声明自身 (*this) 私有(private)的类以避免竞争条件/放弃 gcc 中线程私有(private)的请求

c++ - 链接器错误,在 ubuntu 15.04 上使用 OpenCV 和 Eclipse CDT

c++ - 可变参数模板参数转发使用逗号运算符

c++11 getline 询问输入的两倍

c++ - 使用带有回调的可变参数模板

c++ - 为什么 clang 将相同类型报告为不兼容?

c++ - C++-没有规则来创建目标SaltPepper.o

c++ - 将方法限制为 C++ 中的少数类

javascript - dust.js 过滤 json 结果

c++ - g++ 使用 -Wpedantic 选项 : Is there an option to disable only the warning about unnamed structs? 编译 C++11