Val*_*rij 2 c++ templates tuples return-type c++11
我想std::tuple_cat从我的函数返回结果,但我没有推断出返回类型
#include <tuple>
struct H {
typedef std::tuple<int,int> tuple_type;
tuple_type a {1,2};
};
template <typename tuple_holder_type, typename B>
???
func(tuple_holder_type h, B b) {
return std::tuple_cat(h.a,std::make_tuple(b));
}
int main(int argc, char const *argv[]) {
auto h = H();
auto b = 3;
auto c = func(h,b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试图结合std::result_of并std::tuple_cat喜欢这个
typename std::result_of<std::tuple_cat(tuple_holder_type::tuple_type,std::tuple<B>) >::type
Run Code Online (Sandbox Code Playgroud)
但只收到错误消息
test.cpp:9:85: error: template argument 1 is invalid
test.cpp:9:86: error: expected identifier before '::' token
test.cpp:10:1: error: expected initializer before 'func'
Run Code Online (Sandbox Code Playgroud)
问题是:我为此付出了什么而不是问号
奖金问:为什么会有效
编辑
忘了提到我需要这样一种方式,我可以把结果类型放在一个typedef,导致类似的东西
template <typename tuple_holder_type, typename B>
struct tuple_appender {
typedef ??? return_type;
return_type operator() /*...*/
}
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
在C++ 11中,您可以这样使用decltype:
template <typename tuple_holder_type, typename B>
auto
func(tuple_holder_type h, B b)
-> decltype(std::tuple_cat(h.a,std::make_tuple(b)))
{
return std::tuple_cat(h.a,std::make_tuple(b));
}
Run Code Online (Sandbox Code Playgroud)
在C++ 1y工作草案中,您可以删除decltype如下:
template <typename tuple_holder_type, typename B>
auto
func(tuple_holder_type h, B b)
{
return std::tuple_cat(h.a,std::make_tuple(b));
}
Run Code Online (Sandbox Code Playgroud)
以下是如何获得返回类型func并将其放入a中typedef,无论func返回类型如何编码:
template <typename tuple_holder_type, typename B>
struct tuple_appender {
typedef decltype(func(std::declval<typename tuple_holder_type::tuple_type>(),
std::declval<std::tuple<B>>())) return_type;
};
Run Code Online (Sandbox Code Playgroud)
std::declval<T>()只是一种获得类型的右值表达式T而不必默认构造一个的方法,比如T().您可能不想假设它T是默认的可构造的.您还可以得到的左值表达式T用declval<T&>(),或者用一个const左值表达式declval<const T&>(),等等.
| 归档时间: |
|
| 查看次数: |
1908 次 |
| 最近记录: |