模板参数默认为后一个 [英] Template parameter default to a later one
问题描述
此链接无法回答我的问题,所以我会在这里问:
This link doesn't answer my question so I'll ask it here:
基本上我想写一个模板函数
Basically I want to write a template function
template <typename Out, typename In>
Out f(In x);
这里我总是需要指定 Out
调用 f
。我不想每次都这样做,所以我基本上想要
Here I always need to specify Out
when calling f
. I don't want to do it every time, so I basically want
template <typename Out = In, typename In>
Out f(In x);
这意味着如果我不指定 Out
,它将默认为 In
。但是,这在C ++ 11中是不可能的。
Which means if I don't specify Out
, it will default to In
. However, this is not possible in C++11.
所以我的问题是,是否有任何方式实现效果:
So my question is, is there any way to achieve the effect:
- 调用
f(t)
将实例化f
code>或更常见的 f
- c> f U(t)将实例化
f
- calling
f(t)
will instantiatef<T,T>(t)
or more generallyf<typename SomeThing<T>::type, T>
- calling
f<U>(t)
will instantiatef<U, T>(t)
推荐答案
我有一个PERFECT解决方案! f< const int&>
将无法工作,因为函数无法返回对临时的引用,与此处使用的技术无关。
I have a PERFECT solution here! f<const int&>
won't work because a function can't return a reference to a temporary, not related to the techniques used here.
[hidden]$ cat a.cpp
#include <iostream>
#include <type_traits>
#include <typeinfo>
using namespace std;
template <typename Out, typename In>
Out f_impl(In x) {
cout << "Out=" << typeid(Out).name() << " " << "In=" << typeid(In).name() << endl;
return Out();
}
template <typename T, typename... Args>
struct FirstOf {
typedef T type;
};
template <typename T, typename U>
struct SecondOf {
typedef U type;
};
template <typename... Args, typename In>
typename enable_if<sizeof...(Args) <= 1, typename FirstOf<Args..., In>::type>::type f(In x) {
typedef typename FirstOf<Args..., In>::type Out;
return f_impl<Out, In>(x);
}
template <typename... Args, typename In>
typename enable_if<sizeof...(Args) == 2, typename FirstOf<Args...>::type>::type f(In x) {
typedef typename FirstOf<Args...>::type Out;
typedef typename SecondOf<Args...>::type RealIn;
return f_impl<Out, RealIn>(x);
}
int main() {
f(1);
f(1.0);
f<double>(1);
f<int>(1.0);
f<int>(1);
f<const int>(1);
f<int, double>(1);
f<int, int>(1);
f<double, double>(1);
}
[hidden]$ g++ -std=c++11 a.cpp
[hidden]$ ./a.out
Out=i In=i
Out=d In=d
Out=d In=i
Out=i In=d
Out=i In=i
Out=i In=i
Out=i In=d
Out=i In=i
Out=d In=d
这篇关于模板参数默认为后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!