这有可能吗?我希望它能够在编译时传递参数。假设它只是为了方便用户,因为总是可以用 template<class T, T X>
键入真实类型, 但对于某些类型,即指向成员函数的指针,即使使用 decltype
也是非常乏味的。作为捷径。考虑以下代码:
struct Foo{
template<class T, T X>
void bar(){
// do something with X, compile-time passed
}
};
struct Baz{
void bang(){
}
};
int main(){
Foo f;
f.bar<int,5>();
f.bar<decltype(&Baz::bang),&Baz::bang>();
}
是否可以将其转换为以下内容?
struct Foo{
template<auto X>
void bar(){
// do something with X, compile-time passed
}
};
struct Baz{
void bang(){
}
};
int main(){
Foo f;
f.bar<5>();
f.bar<&Baz::bang>();
}
最佳答案
更新后:没有。 C++中没有这样的功能。最接近的是宏:
#define AUTO_ARG(x) decltype(x), x
f.bar<AUTO_ARG(5)>();
f.bar<AUTO_ARG(&Baz::bang)>();
听起来你想要一个发电机:
template <typename T>
struct foo
{
foo(const T&) {} // do whatever
};
template <typename T>
foo<T> make_foo(const T& x)
{
return foo<T>(x);
}
现在不用拼写:
foo<int>(5);
你可以这样做:
make_foo(5);
推导论点。
关于c++ - 是否可以模拟模板<auto X>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13350571/