【发布时间】:2020-09-13 07:18:34
【问题描述】:
我正在尝试使用 switch 语句在我的 C++11 程序中将运行时常量转换为编译时常量。我有enum SomeEnum {A, B, C};,根据它的值,我想调用模板函数f<A>()、f<B>() 或f<C>()。我的代码中有很多依赖于SomeEnum(以及其他模板参数)的模板函数,所以我决定制作专用的dispatch 函数。这是我要编译的代码:
#include <utility>
enum SomeEnum {
A, B, C
};
template<template<SomeEnum, typename...> class FUNCTOR, typename ...OTHERS, typename ...ARGS> inline auto dispatch (
SomeEnum const type,
ARGS&&... args
) -> decltype( FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...) ) { //Problem here
switch(type) {
case A:
return FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...);
case B:
return FUNCTOR<B, OTHERS...>::function(std::forward<ARGS>(args)...);
case C:
return FUNCTOR<C, OTHERS...>::function(std::forward<ARGS>(args)...);
default:
//Do not call any function if enum value is wrong, just return something:
return decltype( FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...) )();
}
}
template<SomeEnum T> struct TemplateFunctor1 {
static inline int function(int) { return 0; }
};
template<SomeEnum T, class OTHER> struct TemplateFunctor2 {
static inline int function(int) { return 0; }
};
int main(void) {
dispatch<TemplateFunctor1>(B, 0); //Problem here!
dispatch<TemplateFunctor2, int>(B, 0);
return 0;
}
(函数返回类型依赖于模板参数的情况我不需要处理)
编译dispatch<TemplateFunctor1>(B, 0); 行时出现错误,其中TemplateFunctor1 只需要一个模板参数。错误信息如下:
error: no matching function for call to 'dispatch(SomeEnum, int)'
note: candidate: template<template<SomeEnum <anonymous>, class ...> class FUNCTOR, class ... OTHERS, class ... ARGS> decltype (FUNCTOR<(SomeEnum)0u, OTHERS ...>::function((forward<ARGS>)(dispatch::args)...)) dispatch(SomeEnum, ARGS&& ...)
note: template argument deduction/substitution failed
error: wrong number of template arguments (2, should be 1) 在这部分代码中:FUNCTOR<A, OTHERS...> 的尾随返回类型。
所以我尝试将尾部返回类型中的FUNCTOR<A, OTHERS...> 更改为FUNCTOR<A>,然后dispatch<TemplateFunctor2, int>(B, 0); 行无法编译。它说我提供了错误数量的模板参数(1,应该是 2),这是一个相当预期的错误。
我在这里不明白的是为什么相同的decltype() 构造在default switch 分支中有效,但在尾随返回类型中无效?
我可以通过将标准更改为 C++14 并完全删除尾随返回类型来修复我的代码,但是我不明白这里发生了什么。
我还尝试了不同的编译器(ICC、GCC、Clang),它们都给出了类似的错误消息,所以这里不可能是编译器错误。
【问题讨论】:
-
gcc 编译这个。
标签: c++11 variadic-templates trailing-return-type