gpt4 book ai didi

c++ - 这个 C++11 可变求和函数的实现有什么问题(如果有的话)?

转载 作者:行者123 更新时间:2023-11-30 00:57:26 28 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
trailing return type using decltype with a variadic template function

我遇到这个编译器错误:

g++ -std=gnu++0x -I. -O3 -Wall sum.cpp
sum.cpp:7:41: sorry, unimplemented: cannot expand ‘Remaining ...’ into a fixed-length argument list
sum.cpp: In function ‘int main(int, const char**)’:
sum.cpp:29:23: error: no matching function for call to ‘sum(int, int, int)’
sum.cpp:29:23: note: candidate is:
sum.cpp:20:6: note: template<class FirstArg, class ... RemainingArgs> decltype (Sum<FirstArg, RemainingArgs ...>::sum(first, sum::args ...)) sum(const FirstArg&, const RemainingArgs& ...)

对于这个sum.cpp:

#include <iostream>
#include <type_traits>

template <typename First, typename... Remaining>
struct Sum {
static auto sum(const First &arg, const Remaining &... args)
-> decltype(arg + Sum<Remaining...>::sum(args...))
{
return arg + sum(args...);
}
};

template <typename First>
struct Sum<First>
{
static First sum(const First &arg) { return arg; }
};

template <typename FirstArg, typename... RemainingArgs>
auto sum(const FirstArg &first, const RemainingArgs &... args)
-> decltype(Sum<FirstArg, RemainingArgs...>::sum(first, args...))
{
return Sum<FirstArg, RemainingArgs...>::sum(first, args...);
}

int main(int argc, const char *argv[])
{
using ::std::cout;
cout << sum(1, 2, 3) << '\n';

return 0;
}

我已经尝试过多种方法来声明这个函数。这只是 gcc 4.6.1 的问题吗?


编辑:这是我最终采用的方法,因为我不太信任 ::std::common_type 模板。但是它仍然有一个问题,它将 + 从右到左而不是从左到右绑定(bind)。这可能会导致非交换 + 运算符出现问题。不过这并不难解决:

#include <iostream>
#include <type_traits>
#include <utility>

namespace {
template<class T> typename ::std::add_rvalue_reference<T>::type val();

template<class T> struct id{typedef T type;};

template<class T, class... P> struct sum_type;
template<class T> struct sum_type<T> : id< T > {};
template<class T, class U, class... P> struct sum_type<T,U,P...>
: sum_type< decltype( val<const T&>() + val<const U&>() ), P... > {};
}

template <typename T>
T sum(const T &&arg)
{
return ::std::forward<const T>(arg);
}

template <typename FirstArg, typename SecondArg, typename... RemainingArgs>
auto sum(const FirstArg &&first, const SecondArg &&second,
const RemainingArgs &&... args)
-> typename sum_type<FirstArg, SecondArg, RemainingArgs...>::type
{
using ::std::forward;

return forward<const FirstArg>(first) + \
sum(forward<const SecondArg>(second),
forward<const RemainingArgs>(args)...);
}

int main(int argc, const char *argv[])
{
using ::std::cout;
cout << sum(1, 2, 3.2) << '\n';

return 0;
}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com