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