pla*_*cel 9 c++ templates c++11
我正面临一个问题,我正在尝试使用特定类型的参数包创建一个可变成员函数.
template <typename T>
struct A
{
using result_type = T;
T operator()(T a, T b)
{
return a+b;
}
};
template <typename Functor>
struct B
{
using T = typename Functor::result_type;
T operator()(Functor &&f, T... args)
{
return f(args...);
}
};
Run Code Online (Sandbox Code Playgroud)
它应该像以下一样工作:
A<int> a;
B<A<int>> b;
int result = b(a, 2, 3); // should return 5
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
error: type 'T' (aka 'typename Functor::result_type') of function parameter pack does not contain any unexpanded parameter packs
T operator()(Functor &&f, T... args)
~^~~~~~~~
error: pack expansion does not contain any unexpanded parameter packs
return f(args...);
~~~~^
Run Code Online (Sandbox Code Playgroud)
实现预期功能的正确方法是什么?
仅当函数是函数模板时才能使用参数包。
来自http://en.cppreference.com/w/cpp/language/parameter_pack:
模板参数包是接受零个或多个模板实参(非类型、类型或模板)的模板参数。函数参数包是接受零个或多个函数参数的函数参数。
具有至少一个参数包的模板称为可变参数模板。
template <typename ... Args>
T operator()(Functor&& f, Args... args)
{
return f(args...);
}
Run Code Online (Sandbox Code Playgroud)
&&此外,只有当它是模板参数时,在上述函数中使用才有意义。当您在&&类型不为模板参数的情况下使用参数时,您不能使用:
A<int> a;
B<A<int>> b;
int r = b(a, 2, 3);
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用
int r = b(std::move(a), 2, 3);
Run Code Online (Sandbox Code Playgroud)
做出你的选择。保持参数类型不变并使用std::move(a)或更改函数以使用简单引用
template <typename ... Args>
T operator()(Functor& f, Args... args)
{
return f(args...);
}
Run Code Online (Sandbox Code Playgroud)
并使用
int r = b(a, 2, 3);
Run Code Online (Sandbox Code Playgroud)
更新
您可以使用辅助类来确保所有参数的类型正确。
template<typename ... Args> struct IsSame : public std::false_type {};
template<typename T> struct IsSame<T> : public std::true_type {};
template<typename T, typename ... Args> struct IsSame<T, T, Args...> : public std::true_type
{
static const bool value = IsSame<T, Args ...>::value;
};
Run Code Online (Sandbox Code Playgroud)
并使用:
template <typename ... Args>
T operator()(Functor&& f, Args... args)
{
static_assert(IsSame<T, Args...>::value, "Invalid argument type");
return f(args...);
}
Run Code Online (Sandbox Code Playgroud)
接着就,随即,
A<int> a;
B<A<int>> b;
int r = b(std::move(a), 2, 3);
Run Code Online (Sandbox Code Playgroud)
仍然有效但是
r = b(std::move(a), 2, 3.0);
Run Code Online (Sandbox Code Playgroud)
失败。
我不知道您的情况是否需要对参数类型如此严格。如果你需要的话,你有办法。