【发布时间】:2020-09-11 09:10:19
【问题描述】:
我正在尝试在 C++14 中调用具有正确数量参数的函数。我有一个模板类,它根据模板过滤器定义自身或 void 的别名:参数被跳过或传递,如下所示:
template<typename comp>
struct exclude {};
template<typename comp>
struct shouldPassComponent
{
using type = comp;
comp& operator()(comp* component) { return *component; }
const comp& operator()(const comp* component) const { return *component; }
}
// void is aliased instead of the component
template<typename comp>
struct shouldPassComponent<exclude<comp>>
{
using type = void;
void operator()(comp* component) {}
void operator()(const comp* component) const {}
}
// if void, the argument should be skipped/not evaluated instead
std::invoke(func, shouldPassComponent<types>()(comps)...); // error here
不幸的是,它不起作用,因为编译器仍然在参数中评估“void()”(错误:“找不到匹配的重载函数”)。
所以我尝试了非模板的方式,看看是否可行:
void CallFunction();
CallFunction(void()); // error here
但是,编译器错误:“错误 C2672:CallFunction:找不到匹配的重载函数”。所以我想到了 lambda 接受自动参数的事实:
void CallFunction();
auto lambdaTest = [](auto... Arguments)
{
//....
CallFunction(Arguments...);
};
lambdaTest(void()); // error here
当调用 lambdaTest.我在互联网上搜索了几个小时,现在我运气不好。
有什么方法可以防止评估/丢弃来自要传递的可变参数的某些参数?任何解决方案将不胜感激。
【问题讨论】:
-
第一种方法有什么问题?如果您在类定义后添加分号,则此代码有效:
int i = 5; shouldPassComponent<int> spc1; spc1((int*) &i); shouldPassComponent<exclude<int>> spc2; spc2((int*) &i);
标签: c++ arguments c++14 void template-specialization