und*_*ind 9 c++ templates template-templates
我想实现一个函数调用的包装器,它会做这样的事情:
template <template<class> class F>
void Wrapper(int n, F&& f)
{
switch (n)
{
case 1:
f<std::int8_t>();
break;
case 2:
f<std::int16_t>();
break;
default:
break;
}
}
template <class T>
void func()
{
// ... body of func()
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以在代码中进行以下调用:
Wrapper(1, func);
Run Code Online (Sandbox Code Playgroud)
但是上面的代码没有编译,因为F&& f构造是无效的 - 我需要指定参数的具体类型.但是,如果我使函数签名如下:
template <template<class> class F, class T>
void Wrapper(int n, F<T>&& f)
Run Code Online (Sandbox Code Playgroud)
然后我必须使用以下具体类型进行调用f:
Wrapper(1, func<std::int8_t>);
Run Code Online (Sandbox Code Playgroud)
我将无法切换Wrapper.
我该如何实现我需要的行为?
如果您func在编译时知道(即,如果它不是某个函数指针),您可以使用以下解决方案:
template <template <class> typename F>
void Wrapper(int n) {
switch (n) {
case 1: F<std::int8_t>{}(); break;
case 2: F<std::int16_t>{}(); break;
default: break;
}
}
template <typename T>
void func() { std::cout << sizeof(T) << std::endl; }
template <typename T>
struct Func { void operator()() { func<T>(); } };
int main() {
Wrapper<Func>(1);
Wrapper<Func>(2);
}
Run Code Online (Sandbox Code Playgroud)
您可以移动int n到模板参数吗?然后你可以使用 Int2Type 习惯用法:
template<int n> struct ParamType {
using value = ... // here will be std::int8_t or std::int16_t depending on n
}
template <template<class> class F, int n>
void Wrapper(F f) {
f<ParamType<n>::value>();
}
Run Code Online (Sandbox Code Playgroud)