简体   繁体   中英

C++17 Fold Expression not Compiling

first time posting so sorry if I have poor format. I encountered fold expressions for the first time the other day and am trying to get something up and running with them. However, all of my attempts have failed to compile. I've boiled it down to the following:

//test.cpp

template<typename... types>
auto adder(types&... args){
    return (args+...);
}

int main(){return 0;}

And I compiled it with

g++ -std=c++17 test.cpp

And it produces the following errors:

testCode.cpp: In function 'auto adder(types& ...)':
testCode.cpp:5:15: error: expected primary-expression before '...' token
  return (args+...);
               ^
testCode.cpp:5:15: error: expected ')' before '...' token
testCode.cpp:5:18: error: parameter packs not expanded with '...':
  return (args+...);
                  ^
testCode.cpp:5:18: note:         'args'

From everything I've seen this should be working, so if someone can tell me what I'm doing wrong I would greatly appreciate it.

I'm working with xenial linux (on a crouton on chrome OS) and a fresh install of g++.

Maybe like this?

#include <string>
#include <iostream>

using namespace std::literals;

template<typename... T>
auto add(const T&... args) {
        return (args + ...);
}

int main() {
        std::cout << add(1,2,3,4) << "\n";
        std::cout << add("a"s, "b"s, "c"s) << "\n";
        return 0;
}

as Kenzel suspected in the comments, this was a versioning issue with the g++ compiler. Not sure what my computer was installing by default, but going to a linux repository and manually installing a newer version of g++ fixed the issue. Thanks for the help everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM