Jan*_*net 10 c++ templates c++11
我有以下问题,我只是没有看到一个正确的解决方案(也许没有):我有一个模板化的方法,其中返回类型取决于输入类型,并感谢C++ 11 decltype
的返回类型可以很容易地派生,但我还想允许用户在需要时明确定义返回类型.
更正式地说,我有一个模板化的函数f
,我希望可以调用它f(x)
,既没有显式定义输入也没有返回类型.而且我还希望能够像f<ret_t>x()
显式定义的返回类型一样调用它,但输入类型仍然自动派生.
现在,用C++ 11满足第一个约束是很容易的(让我们假设还有另一个模板化的方法:
template<typename InT>
auto f(const InT& in) -> decltype(/* code deriving the return type using in */);
Run Code Online (Sandbox Code Playgroud)
但是这不会允许覆盖返回类型,因为我必须将其添加为第二个模板参数并将decltype
派生移动到模板定义中,并且可能需要使用std::declval<InT>
或std::result_of
:
template<
typename InT,
typename RetT = /* code deriving return type using InT and declval/result_of */>
RetT f(const InT& in);
Run Code Online (Sandbox Code Playgroud)
但是,这种方式我总是需要InT
在调用时明确定义f
.因此f
,为了能够保持InT
开放但声明的声明RetT
应该是:
template<
typename RetT = /* code deriving return type using InT and declval/result_of */,
typename InT>
RetT f(const InT& in);
Run Code Online (Sandbox Code Playgroud)
但是,由于我需要为其指定默认值RetT
,InT
因此尚不可用,因此无法使用.
到目前为止我可以提出的最好的解决方法,这不是很令人满意,并且似乎无论如何都没有工作,因为扣除RetT
失败(显然是因为你不能从默认参数中推断出类型),是:
template<typename RetT, typename InT>
RetT f(
const InT& in,
const RetT& = std::declval</* code deriving return type using InT or in and declval/result_of */>());
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来获得默认值RetT
依赖于,InT
同时仍然能够明确指定RetT
是否需要?重要的是要注意返回类型需要在函数实现中可用,以便RetT
直接在方法体内分配对象.
Mir*_*pas 10
您可以使用std::conditional
和dummy
类型来检查该函数是否具有自动推导类型或用户选择类型.
如果用户显式选择了返回类型,则返回类型将与dummy
类型不同,这将是函数的返回类型.否则只需像以前一样使用推导类型.
以下是一个使用示例:
#include <typeindex>
#include <type_traits>
#include <iostream>
struct dummy
{
};
template<typename RetType = dummy, typename T>
auto f(const T& in)
-> typename std::conditional<std::is_same<RetType, dummy>::value, T, RetType>::type
{
std::cout<<typeid(RetType).name()<<" "<<typeid(T).name()<<std::endl;
return in;
}
int main()
{
f(1);
f<float>(1);
}
Run Code Online (Sandbox Code Playgroud)