Fer*_*eak 3 c++ templates fold-expression c++17 if-constexpr
我正在尝试在函数中创建一个折叠表达式,该函数用来自字符串向量的一些值填充函数的传出参数。我的折叠表达式是这样的:
((if constexpr (std::is_integral_v<Args>)
{
args = std::stoi(vec[index++]);
}
else if constexpr (std::is_same_v<Args, std::string>)
{
args = vec[index++];
}
else
{
throw std::invalid_argument("Unsupported argument type.");
}), ...);
Run Code Online (Sandbox Code Playgroud)
但它无法编译并出现奇怪的错误消息:
clang: error: expected expression
Run Code Online (Sandbox Code Playgroud)
或者
gcc: error: expected primary-expression before 'if'
Run Code Online (Sandbox Code Playgroud)
(如https://gcc.godbolt.org/z/xeq3j6oE7所示)
有人提示如何正确解决此问题吗?
编辑
这个问题的完整背景是这个简短的应用程序:
#include <vector>
#include <string>
#include <type_traits>
#include <iostream>
#include <stdexcept>
template <typename... Args>
void populateArgs(std::vector<std::string>& vec, Args&... args)
{
const size_t numArgs = sizeof...(Args);
if (vec.size() != numArgs)
{
throw std::invalid_argument("Number of arguments doesn't match the size of the vector.");
}
int index = 0;
((if constexpr (std::is_integral_v<Args>)
{
args = std::stoi(vec[index++]);
}
else if constexpr (std::is_same_v<Args, std::string>)
{
args = vec[index++];
}
else
{
throw std::invalid_argument("Unsupported argument type.");
}), ...);
}
int main()
{
std::vector<std::string> vec{ "1", "2", "3", "hello" };
short a;
int b;
long long c;
std::string d;
populateArgs(vec, a, b, c, d);
std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", d = " << d << std::endl;
// Output: a = 1, b = 2, c = 3, d = hello
}
Run Code Online (Sandbox Code Playgroud)
像这样:
([&]{
// if constexpr ...
}(), ...);
Run Code Online (Sandbox Code Playgroud)
这将创建一个 lambda 并立即调用它。
我记得这在 MSVC 上引起了一些问题。如果它不适合您,您可以尝试:
([&]<typename T>()
{
// Use `T` instead of `Args` here.
}.operator()<Args>(), ...);
Run Code Online (Sandbox Code Playgroud)
,或单独的模板函数。
归档时间: |
|
查看次数: |
155 次 |
最近记录: |