据我所知如何pass template function as template argument ,我现在正在努力以类似的方式传递变量模板。
这是我尝试过的最小示例:
#define PASS_VARIABLE_TEMPLATE(name) [dummy=nullptr](auto&&...args) \
{return name<decltype(args)...>;}
//testing
template <typename T>
bool value = std::is_fundamental<T>::value;
template <typename Hax>
void print_bool(Hax h)
{
std::cout << h(int{}) << std::endl; // no error, wrong output
//std::cout << h(int{}, float{}) << std::endl; // error, good
}
int main()
{
print_bool(PASS_VARIABLE_TEMPLATE(value)); //prints 0 instead of 1
}
如果编译通过,为什么输出错误?
最佳答案
您的代码的主要问题是 decltype
将参数推断为 rvalue
引用 (int&&
),因为您的 lambda 使用 转发引用 以接受参数。
std::is_fundamental
将适用于裸类型。
对于您的特定片段,正确的解决方案是 remove the reference .
#define PASS_VARIABLE_TEMPLATE(name) \
[dummy=nullptr](auto&&...args){return name<std::remove_reference_t<decltype(args)>...>;}
现在可以了。 :-) 看看Live On Coliru
稍微多一点或更好的通用方法是另外remove cv预选赛。最后,您可能想使用 std::decay
#define PASS_VARIABLE_TEMPLATE(name) [dummy=nullptr](auto&&...args) \
{return name<std::decay_t<decltype(args)>...>;}
关于c++ - 是否可以通过 lambda 将变量模板传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39944994/